개발 알다가도 모르겠네요

상태가 결정된 Promise 객체 본문

카테고리 없음

상태가 결정된 Promise 객체

이재빵 2021. 7. 21. 00:00
728x90

fulfilled 상태의 Promise 객체 만들기

const p = Promise.resolve('success');

 

rejected 상태의 Promise 객체 만들기

const p = Promise.reject(new Error('fail'));

 

 

 

이미 fulfilled 또는 rejected 상태가 결정된 Promise 객체라도 then 메소드를 붙이면, 콜백에서 해당 작업 성공 결과 또는 작업 실패 정보를 받아올 수 있습니다. 시점과는 전혀 상관이 없습니다.

const p = new Promise((resolve, reject) => {
  setTimeout(() => { resolve('success'); }, 2000); // 2초 후에 fulfilled 상태가 됨
});

p.then((result) => { console.log(result); }); // Promise 객체가 pending 상태일 때 콜백 등록
setTimeout(() => { p.then((result) => { console.log(result); }); }, 5000); // Promise 객체가 fulfilled 상태가 되고 나서 콜백 등록

Promise 객체의 상태가 fulfilled 또는 rejected 상태이기만 하면, 어느 시점이든, 몇 번이든 then 메소드를 붙여서 해당 결과를 가져올 수 있습니다.