[Codecamp-Week7] Promise all

·2022년 8월 16일
0

이전 글에서 promise에 대해 살펴본 적이 있다.

Promise는 async await가 실행되는 것처럼 하나의 Promise가 실행되고 난 후 그 다음 Promise가 실행된다.
만약 이미지 업로드를 할 경우 이미지 하나하나가 하나씩 하나씩 로드된다면 user는 답답함을 느낄 것이다.
이러한 상황에 Promise all을 활용함으로써 user는 한 번에 모든 이미지들이 로드된 화면을 볼 수 있게 된다.

[Promise 살펴보기]

export default function PromiseAllPage() {
  const onClickPromise = async () => {
    // 전체 걸린 시간 콘솔로 보기
    console.time("시작!");
    // 성공하면 resolve, 실패하면 reject (reject는 에러메세지를 가져옴)
    const result1 = await new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("철수");
      }, 3000);
    });
    console.log(result1);

    const result2 = await new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("영희");
      }, 1000);
    });
    console.log(result2);

    const result3 = await new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("훈이");
      }, 2000);
    });
    console.log(result3);

    console.timeEnd("시작!");
  };
  
   return (
      <button onClick={onClickPromise}>Promise 연습하기!</button>
      
  );
}

Promise 연습하기! 버튼을 클릭하면 실행되는 onClickPromise 함수는 3개의 연속적인 Promise로 이루어져 있다.
이를 콘솔로 찍어보면 하나씩 차례대로 3초 후 "철수", 1초 후 "영희", 2초 후 "훈이"가 찍혀 최종적으로 함수 실행에 6초가 걸리는 것을 볼 수 있다.

[Promise all 살펴보기]

export default function PromiseAllPage() {
    const onClickPromiseAll = async () => {
    console.time("시작!");

    const results = await Promise.all([
      new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("철수");
        }, 3000);
      }),
      new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("영희");
        }, 1000);
      }),
      new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("훈이");
        }, 2000);
      }),
    ]);
    console.log(results);

    console.timeEnd("시작!");
  };

  return (
      <button onClick={onClickPromiseAll}>Promise.all 연습하기!</button>
  );
}

Promise all을 활용할 경우, Promise에서 각각 result 1,2,3으로 선언해줬던 Promise들을 하나의 results에 한꺼번에 담을 수 있다.
이렇게 하나의 변수에 담긴 Promise들이 Promise.all을 활용함으로써 가장 시간이 오래 걸리는 철수의 시간에 맞춰 3초 안에 함수가 종료되는 것을 볼 수 있다.

profile
개발을 개발새발 열심히➰🐶

0개의 댓글