Javascript Promise

김하늘·2022년 9월 28일
0

JAVASCRIPT

목록 보기
5/5

promise 는 자바스크립트 비동기 처리에 사용되는 객체!

  • State: 대기(pending)->이행(fulfilled) or 실패(rejected)
  • Producer vs Consumer
  1. Producer
    새로운 promise 가 만들어질 때는 우리가 전달한 executor 라는 콜백함수가 자동적으로 실행된다..! 꼭 염두하기..!!!
const promise = new Promise((resolve, reject) => {
  // doing some heavy work (network, read files)
  // resolve();
  // reject();
});
  1. Consumers: then, catch, finally
    성공했을때 then, 실패했을때 catch, 성공/실패와 상관없이 실행 finally
    ++ then 은 값을 바로 전달해도 되고, 다른 promise를 전달해도 됨다
promise
  .then(value => {
      console.log(value);
  })
  .catch(error => {
      console.log(error);
  })
  . finally(() > {
      console.log('finally');
  });
  1. Promise.all
    promise 배열을 전달하면 모든 promise 들이 병렬적으로 다 받을때까지 모아준다!
function pickAllFruits() {
    return Promise.all([getApple(), getBanana()]).then(fruits => fruits.join(' + '));
}

pickAllFruits().then(console.log);

4.Promise.race
배열에 전달된 promise 들 중에서 가장 먼저 값이 리턴 된 것만 전달되어진다

function pickOnlyOne() {
    return Promise.race([getApple(), getBanana()]);
}

pickOnlyOne().then(console.log);
profile
아 응애에요🐥

0개의 댓글