promiseerror-handling

Promise chaining과 에러 전파를 설명해 주세요

예상 시간
7
30초 답변

꼬리질문

조금 더 깊게 물어본다면

답변 뒤에 이어질 수 있는 질문들을 하나씩 열어볼 수 있어요.

`then` 안에서 Promise를 반환하면 어떻게 되나요?

부가 설명

fetchUser()
  .then((user) => fetchPosts(user.id))
  .then((posts) => posts.slice(0, 3))
  .catch((error) => {
    console.error(error);
    return [];
  })
  .then((posts) => {
    console.log(posts);
  });

첫 번째 then에서 fetchPosts라는 Promise를 반환하면 다음 then은 그 Promise가 fulfilled된 뒤 실행됩니다. 중간에 에러가 나면 catch로 이동합니다. catch가 빈 배열을 반환하면 그 다음 then은 정상 흐름으로 실행됩니다.

Promise chaining에서 자주 생기는 실수는 내부 Promise를 반환하지 않는 것입니다.

fetchUser().then((user) => {
  fetchPosts(user.id); // 반환하지 않음
});

이렇게 쓰면 바깥 chain은 fetchPosts를 기다리지 않습니다. 순서를 보장해야 한다면 return fetchPosts(user.id)처럼 반환해야 합니다.

한 줄 정리

Promise chaining은 각 handler가 새 Promise를 만들고, 반환 값과 에러가 다음 단계로 전파되는 흐름입니다.