프로미스의 기본

Promise 생성자 함수를 new 연산자와 함께 호출하면 프로미스(Promise 객체)를 생성한다. … Promise 생성자 함수는 비동기 처리를 수행할 콜백 함수를 인수로 전달받는데, 이 콜백 함수는 resolve와 reject 함수를 인수로 전달받는다.

프로미스 객체의 구성

구성 요소 설명
[[PromiseState]] pending, fulfilled, rejected 중 하나의 상태 (내부 슬롯, 직접 접근 불가)
[[PromiseResult]] 성공 시 결과 값, 실패 시 오류 객체 (내부 슬롯, 직접 접근 불가)
then, catch, finally 후속 처리 메서드. 전부 새로운 Promise 객체 반환함
{
  [[PromiseState]]: "pending" | "fulfilled" | "rejected",
  [[PromiseResult]]: any,   // 성공 시 결과 or 실패 시 에러
  then(onFulfilled, onRejected),
  catch(onRejected),
  finally(onFinally)
}

후속 처리 메서드

const fulfilled = new Promise((resolve, reject) => {
    setTimeout(() => {
      if (Math.random() > 0.5) resolve(1);
      else reject(2);
    }, 1000);
  })
    .then((res) => console.log(res)) // 건너뜀
    .catch((err) => console.error(err)); // 콘솔에러 2
const prom = (val) =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      if (val > 0.5) resolve(1);
      else reject(2); // 호출됨.
    }, 1000);
  })
    .then((res) => console.log(res)) // 건너뜀
    .finally(() => console.log("finally")) // 콘솔: finally
    .then(() => console.log("then")) // 건너뜀
    .catch((err) => console.error(err)) // 콘솔에러: 2
    .then((res) => console.log(res)) // **(catch 이후엔 then만 태움)**콘솔: undefined
    .catch((err) => console.error(err)); // 건너뜀

prom(0.3);