FLYNNLABAboutMeCodingActivityStudy 2024초등수학링크오프너릴리즈노트WordTest
series and parallel by async / await
2017-08-31
javascript, async-await

async / await로 비동기잡들을 순서대로 혹은 병렬로 실행 시키는 방법을 공유한다.

ts code

    let delayFn = (delayTime) => new Promise((resolve) => {
      console.log(delayTime);
      setTimeout(() => resolve(delayTime), delayTime);
    });

    async function asyncMain() {
      const result = [];
      for (const delayTime of [100, 1000, 500]) {
        result.push(await delayFn(delayTime));
      }
      return result;
    }

    async function asyncMain2() {
      const result = [];
      const resultFn = [];
      for (const delayTime of [100, 1000, 500]) {
        resultFn.push(delayFn(delayTime));
      }
      for (const delay of resultFn) {
        result.push(await delay);
      }
      return result;
    }

    (async function run() {
      console.time('asyncMain');
      console.log(await asyncMain());
      console.timeEnd('asyncMain');
      console.time('asyncMain2');
      console.log(await asyncMain2());
      console.timeEnd('asyncMain2');
    })();

result

asyncMain: 1907.22802734375ms
asyncMain2: 1009.010009765625ms