js Promise, Promise.all, Promise.race

kdh3543·2023년 2월 1일
0

Promise vs Promise.all vs Promise.race

Promise

  • 시간이 걸리는 작업을 할 때 사용함

Promise.all

  • 요청이 한번에 보내짐(promise는 한번에 하나씩만 요청이 감)
  • promise 요청을 한번에 배열에 담아 보내고, 결과도 배열로 한번에 받음

Promise.race

  • promise 요청을 병렬로 요청하지만 가장 먼저 완료된 요청만 리턴시킴
  • 비동기 요청의 timeout을 설정할 수 있음
const timeout = new Promise((resolve, reject) => {
 const id = setTimeout(() => {
   clearTimeout(id);
   reject('timeout!');
 }, 500);
});
const promise = new Promise((resolve, reject) => {
  const id = setTimeout(() => {
    clearTimeout(id);
    resolve('response!');
  }, 700);
});
Promise.race([promise, timeout]).then(response => {
  console.log(response);
}).catch(err => {
  console.log(err) //timeout!
});

Promise vs Promise.all

  • 소요시간
    ==> promise로 요청시 각각 하나씩 실행되어 시간이 오래걸리지만 promise.all은 병렬적으로 실행되어 시간이 단축됨

promise

const onClickPromise = async () => {
    console.time("Promise 요청");
    const result1 = await new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("https://dog1.jpg");
      }, 3000);
    });
    console.log(result1);
    const result2 = await new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("https://dog2.jpg");
      }, 1000);
    });
    console.log(result2);
    const result3 = await new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("https://dog3.jpg");
      }, 2000);
    });
    console.log(result3);
    console.timeEnd("Promise 요청"); // 6초
  };

promise.all

const onClickPromiseAll = async () => {
    console.time("PromiseAll 요청");
    const result = await Promise.all([
      new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("https://dog1.jpg");
        }, 3000);
      }),
      new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("https://dog2.jpg");
        }, 1000);
      }),
      new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("https://dog3.jpg");
        }, 2000);
      }),
    ]);
    console.timeEnd("PromiseAll 요청"); // 3초
  }

*결론
간단한 요청시에는 Promise로 처리해도 상관은 없지만 많은 요청이 필요할 때에는 Promise.all로 요청하는게 더 효율적이다.

profile
북한코뿔소

0개의 댓글