🙆

promiseをforeachで扱う[js]

に公開

非同期処理めんどい

全部発火させて終了
const arr = [100, 400, 200];
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
arr.forEach(async (v, i) => {
    await sleep(v);
    console.log(v, i);
});
console.log('finish');

// console result:
// finish
// 100, 0
// 200, 2
// 400, 1

仕事を頼むことが目的なイメージ。

全部発火させて終了するまで待つ
const arr = [100, 400, 200];
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
await Promise.all(arr.map(async (v, i) => {
    await sleep(v);
    console.log(v, i);
}));
console.log('finish');

// console result:
100, 0
200, 2
400, 1
finish

仕事を並行で頼んで、全部できたら終了のイメージ。

一つずつ発火させて実行する
const arr = [100, 400, 200];
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
await arr.reduce((p, v, i) => p.then(async () => {
  await sleep(v);
  console.log(v, i);
}), Promise.resolve());
console.log('finish');

// console result:
100, 0
400, 1
200, 2
finish

仕事を一つずつ順番にやってもらうイメージ。

p.s.

参考にさせていただきました。
https://zenn.dev/wintyo/articles/2973f15a265581

Discussion