-
fetch의 함정(?); fetch는 resolve된 프로미스다.Web/Error & Fix 2022. 6. 11. 21:39SMALL
드디어 3주에 걸친 자스 기초 스터디가 끝나고
평화롭게 깜지를 적고 있었던 중
동기 분의 질문이 올라왔다.
Q.
"fetch의 url이 잘못되었는데, catch가 바로 실행되지 않고
then 안의 console.log가 실행돼요!"
const f = fetch('https://raw.githubusercontent.com/paullabkorea/coronaVaccinationStatus/main/data/data.jsonㄹㄴㅇ') .then(data => { console.log('데이터 받기 성공!') const jsonData = data.json() return jsonData }) .then(json => { json.forEach(item => { console.log(item) const h2 = document.createElement('h2') h2.innerText = item['시·도별(1)'] document.body.append(h2) const p = document.createElement('p') p.innerText = item['총인구 (명)'] document.body.append(p) }) }) .catch(e => { console.log('json 변환 실패!!') })console 결과:

음? then 자체는 resolve 된 값일 때 실행되는 것인데 왜
then 안의 console.log가 실행되었을까?
정답은 바로
fetch 자체가 resolve(fulfilled)된 프로미스라는 점이었다.

fulfilled된 프로미스를 리턴하는 메소드 = fetch 
url이 잘못되면 보통 http에러가 나타나는데, 이를 reject 하지 않는 특징이 있었다..!
그래서 then 안의 console.log는 일단 제대로 실행은 됐으나
url이 잘못되어 제대로 데이터를 갖고오지 못해 return 을 할 수 없었으므로
그때 catch로 가는 것이었다!
그래서 console.log 코드를 데이터 가져오는 코드보다 뒤에다 배치하면 아예 실행이 안된다.
반응형'Web > Error & Fix' 카테고리의 다른 글
드롭다운 구현에서 blur와 click 이벤트, 그리고 CSS transition의 영향.. (0) 2022.05.17