강의

멘토링

로드맵

인프런 커뮤니티 질문&답변

c3392302님의 프로필 이미지
c3392302

작성한 질문수

한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지

2.10) Date 객체와 날짜

바로 res.json()을 리턴할 경우

작성

·

1.1K

0

안녕하세요 선생님 위의 코드는 잘 작동하지만 두번째 코드는 프로미스 객체자체를 반환하던데 어떤 차이가 있나요? 둘 다 res.json()을 콘솔에 띄우는 코드 아닌가요??

let response = fetch("https://jsonplaceholder.typicode.com/posts")

.then((res) => {

return res.json();

})

.then((jsons) => {

console.log(jsons);

});

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

답변 1

0

이정환 Winterlood님의 프로필 이미지
이정환 Winterlood
지식공유자

안녕하세요 이정환입니다.

천천히 설명드려볼게요 😃

위 코드는 첫번째 then 메서드에서 res.json()을 반환하고 있지요?
이때 res.json() 메서드는 비동기 작업이라서 사실 Promise 객체를 반환한답니다.
그래서 res.json()을 반환하는 then 메서드의 반환값은 결국 Promise 객체가 됩니다.

따라서 다음 예제 코드에서 변수 response에는 Promise 객체가 저장되게 되는 것이죠
(res.json이 비동기 함수이기 때문에요!)

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

그래서 res.json 메서드의 진짜 결과값(비동기 작업의 결과값)을 사용하고 싶다면 다음 예제 코드처럼 한 번 더 then 메서드를 사용해 주어야 합니다.

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

왜 그럴까요?
앞서 이야기했듯이 첫번째 then 메서드의 반환값은 res.json이고 이 메서드는 Promise 객체를 반환하기 때문이에요

image

 

그럼 이렇게 생긴 코드는 어떨까요?
당연히 res.json 메서드의 결과값은 Promise 객체이기 때문에 Promise 객체가 출력되는 것 입니다.

let responses = fetch("https://jsonplaceholder.typicode.com/posts").then(
  (res) => {
    console.log(res.json());
  }
);
c3392302님의 프로필 이미지
c3392302

작성한 질문수

질문하기