ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

ํ•˜๋‚˜์˜ async function ๋‚ด์—์„œ๋Š” await ํ‚ค์›Œ๋“œ๋ฅผ ๋งŒ๋‚  ๋•Œ๋งˆ๋‹ค
๋ง ๊ทธ๋Œ€๋กœ ๊ธฐ๋‹ค๋ ธ๋‹ค๊ฐ€(await) ๋น„๋™๊ธฐ์ฒ˜๋ฆฌ๊ฐ€ ์™„๋ฃŒ ๋œ ํ›„ ์ง๋ ฌ๋กœ ๋‹ค์Œ task๋ฅผ ์ฒ˜๋ฆฌํ•œ๋‹ค.

๋งŒ์•ฝ์— async ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ๊ตฌํ˜„ํ–ˆ๋˜ ๊ณผ์ œ ์ค‘์— each๋‚˜ times ์ฒ˜๋Ÿผ
์—ฌ๋Ÿฌ ๋น„๋™๊ธฐ task๋ฅผ ๋ณ‘๋ ฌ์ ์œผ๋กœ ์‹œ์ž‘์‹œํ‚ค๋ ค๋ฉด ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ• ๊นŒ?

๋งŒ์•ฝ Promise.all ๊ฐ€ ๋ณ‘๋ ฌ๋กœ ๋™์ž‘ํ•œ๋‹ค๋ฉด ์š”๊ฑธ ์“ฐ๋ฉด ๋  ๊ฒƒ ๊ฐ™๋‹ค!!
๊ทธ๋ž˜์„œ ํ•œ๋ฒˆ ํ™•์ธํ•ด๋ณด์•˜๋‹ค.

โ€‹

async/await ์ง๋ ฌ์ฒ˜๋ฆฌ

function nSecondsLater(n) {
  console.log(`๐Ÿšฉ n=${n} Start`);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`โœ… ${n} Seconds Later`);
    }, n * 1000);
  });

}

const arr = [0, 1, 2, 3]


async function asyncWaterfall() {
  for (let n of arr) {
    const promise = await nSecondsLater(n);
    console.log(promise);
  }
  console.log("DONE!");
}

asyncWaterfall();

async/await : for of๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ ์ˆœํšŒ ํ•  ๊ฒฝ์šฐ
์•„๋ž˜์™€ ๊ฐ™์ด waterfall ํ˜•ํƒœ๋กœ ์‹คํ–‰๋œ๋‹ค.

 

asyncWaterfall

โ€‹

Promise.all()์„ ์ด์šฉํ•œ ๋ณ‘๋ ฌ์ฒ˜๋ฆฌ

function asyncParallel() {
  const promises = arr.map(n =>
    nSecondsLater(n).then(console.log)
  );
  Promise.all(promises).then(() => console.log("DONE!"));
}

asyncParallel();

์œ„์™€ ๊ฐ™์ด Promise.all()์„ ์ด์šฉํ•˜์—ฌ ํ•œ๋ฒˆ์— ์ฒ˜๋ฆฌํ•  ๊ฒฝ์šฐ
์•„๋ž˜์™€ ๊ฐ™์ด ์›ํ•˜๋Š” ๋Œ€๋กœ ๋ณ‘๋ ฌ๋กœ ๋™์ž‘ํ•œ๋‹ค!

 

asyncParallel

โ€‹

 

์ถ”๊ฐ€!
+ async/await ์—†์ด waterfall ๊ตฌํ˜„ํ•˜๊ธฐ

function asyncWaterfall2() {
  const promise = arr.reduce((accPromise, n) => {
    return accPromise.then(() => {
      return nSecondsLater(n).then(console.log);
    });
  }, Promise.resolve());
  promise.then(() => console.log("DONE!"));
}

asyncWaterfall2();

 

์—ฌ์ „ํžˆ ์•„์ง์€ ๋น„๋™๊ธฐ ๋ฌธ๋ฒ•๋“ค์ด ์ต์ˆ™์นœ ์•Š์ง€๋งŒ ์—ฌ๋Ÿฌ๊ฐ€์ง€ ์˜ˆ์ œ์ฝ”๋“œ๋ฅผ ์ž์ฃผ ์งœ๋ด์•ผ๊ฒ ๋‹น

๋Œ“๊ธ€