.then().then()

이서현·2022년 4월 26일
0

왜 then이 두 번 반복될까?


fetch("https://jsonplaceholder.typicode.com/posts").then((response) => {
  console.log(response);
});

fetch()는 Response object를 반환한다.
근데 나는 json데이터가 필요한데 어떻게 해야 하지?
여기서 then이 두 번 호출되는 이유가 나온다.
Response object 의 json 함수를 호출하고, return을 해줘야 한다!(=return response.json();)
그러면 두 번째 then 함수에서 응답 body의 데이터를 받을 수 있다!

fetch("https://jsonplaceholder.typicode.com/posts").then((response) => {
  console.log(response);
  return response.json();
}).then((data) => console.log(data));

json() : The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON.



또 내가 헷갈려한 이유는 화살표 함수를 쓸 때
return을 생략해도 된다는 사실을 까먹어서 그렇다.
축약이 되어있어 코드를 제대로 해석하지 못했다. 잊지 말자🧠

// 1
.then((response)=> response.json());
// 2
.then((response)=> {
	return response.json();
});

두 개 모두 동일한 코드




참고: https://yeri-kim.github.io/posts/fetch/

profile
🌿💻💪🧠👍✨🎉

0개의 댓글