Promise 체이닝과 then → catch → then 흐름

rada·2025년 4월 6일
0

개발

목록 보기
37/43

example

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("완료");
  }, 1000);
});

promise
  .then(result => {
    console.log(result);              // 출력: 완료
    throw new Error("에러발생");     // 에러 던짐
  })
  .catch(error => {
    console.log(error.message);       // 출력: 에러발생
    return "복구됨";                  // 에러 복구 → 다음 then으로 전달됨
  })
  .then(result => {
    console.log(result);              // 출력: 복구됨
  });

✅ 실행 순서 분석

1️⃣ new Promise(...):

  • 1초 뒤 resolve("완료") 실행

2️⃣ .then(result => { ... }):

  • result === "완료"
  • console.log("완료") 출력
  • throw new Error("에러발생") → 에러 발생!

3️⃣ .catch(error => { ... }):

  • 에러 메시지 "에러발생" 출력
  • "복구됨" 문자열 리턴 → 다음 then으로 넘어감

4️⃣ .then(result => { ... }):

  • 전달받은 "복구됨" 출력

🖨 최종 출력:

완료
에러발생
복구됨

🔍 흐름 요약

resolve("완료")
  ↓
.then → 출력 후 에러 발생
  ↓
.catch → 에러 메시지 출력, 복구 문자열 리턴
  ↓
.then → 복구 결과 출력

🧠 팁

  • catch()는 이전 체인의 에러를 "잡고" 복구하거나 리턴 가능
  • catch()에서 값을 리턴하면, 다음 then으로 전달
  • 다시 throw하면 체인은 다시 실패 상태로 전환됨
profile
So that my future self will not be ashamed of myself.

0개의 댓글