Promise Chaining

Happhee·2022년 5월 12일
1

AvenJS

목록 보기
14/17
post-thumbnail

✨ Promise chaining

콜백 지옥을 피해서 순차적인 비동기 작업을 수행하도록 한다.

예제로 알아보기

const promiseFruitDelay = fruit => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(fruit);
      if (fruit) {
        resolve(fruit);
      }
      reject(new Error('❗️ empty fruit ❗️'));
    }, 1000);
  });
};
const createPromise = promiseFruitDelay('CREATE');

createPromise
  .then((value) => '🍎')
  .then((value) => promiseFruitDelay('🍊'))
  .finally(() => console.log('~ING'))
  .then((value) => promiseFruitDelay('🍋'))
  .then((value) => promiseFruitDelay('🍑'))
  .catch((err) => console.log(err))
  .finally(() => console.log('END'));

비동기 작업을 Promise를 이용해서 원하는 순서대로 과일을 출력하였다.

코드 과정

  1. then/catch/finally 메소드Promise 객체 자체를 반환

  2. 이어서 then을 호출

  3. 만약 then의 핸들러가 값을 반환

    • 해당 Promise 객체의 result
    • 이어지는 then의 핸들러에서 인자로 받아 사용
  4. 핸들러에서 Promise 객체를 생성하거나 반환

    • 이어지는 후속 처리 메소드의 핸들러(다음 핸들러)는
      해당 Promise가 처리될 때까지 기다리다가 처리가 완료되면 그 결과값을 인자로 받아 사용
  5. 콜백을 중첩하지 않고도 이어서 비동기 작업을 할 수 있는 Promise 체이닝이 가능하다.


📚 학습할 때, 참고한 자료 📚

profile
즐기면서 정확하게 나아가는 웹프론트엔드 개발자 https://happhee-dev.tistory.com/ 로 이전하였습니다

0개의 댓글