Promise all

wony·2022년 4월 26일
0

Promise all?

비동기 처리를 위한 방법으로는

  1. 콜백함수
  2. Promise
  3. Async/Await
  4. Promise all
    등이 있다

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초 정도의 시간이 걸린다


promiseall을 이용하면

  const onClickPromiseAll = async () => {
   
    console.time("PromiseAll 시작");
    const result = await Promise.all(
      ["https://dog1.jpg", "https://dog2.jpg", "https://dog3.jpg"].map(
        (el) =>
          new Promise((resolve, reject) => {
            setTimeout(() => {
              resolve(el);
            }, 3000);
          })
      )
    );
    console.log(result);
    console.timeEnd("PromiseAll 시작");
  };


3초의 시간이 걸린다
promise보다 훨씬 빠르게 진행할 수 있다

promise all은 병렬로 비동기 함수를 실행시켰기 때문에 훨씬 빠른것이다

또 다른 장점으로는 에러가 발생했을 때 그 실패를 즉시 반환한다
promise를 이용하면 함수가 종료되고 에러를 반환하지만
promise all을 이용하면 비동기 함수가 병렬로 실행되기 때문에
실행순서와는 상관 없이 가장 빨리 에러를 반환하는 함수의 시간을 기준으로 동작이 종료된다

profile
무럭무럭 성장중🌿

0개의 댓글