2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

この記事誰得? 私しか得しないニッチな技術で記事投稿!

Node.jsで複数回の非同期処理をするときはPromise.allを使うと早く終わる

Posted at

はじめに

非同期処理を複数回実行する時は、直列で実行するより並列で実行する方が早く終わるよ、という話
処理によっては直列で実行しないといけない場合はあると思うけど、その必要性が無い場合は並列実行する方が処理速度の恩恵を受けれる。

プログラム

index.mjs
const sleep = s => new Promise(res => setTimeout(res, s * 1000));

const log = (message) => { console.log(`[${new Date()}] ${message}`); }

const seconds = [3, 4, 5];

const nonUsePromiseAll = async () => {
  log(`nonUsePromiseAll start`);
  for (const second of seconds) {
    await sleep(second);
    log(`nonUsePromiseAll, second: ${second}`);
  }
  log(`nonUsePromiseAll end`);
}

await nonUsePromiseAll();

console.log('------------------');

const usePromiseAll = async () => {
  log(`usePromiseAll start`);
  const promises = seconds.map(async second => {
    await sleep(second);
    log(`usePromiseAll, second: ${second}`);
  })
  await Promise.all(promises)
  log(`usePromiseAll end`);
}

await usePromiseAll();

実行結果

$ node index.mjs
[Thu Jun 29 2023 16:29:48 GMT+0900 (Japan Standard Time)] nonUsePromiseAll start
[Thu Jun 29 2023 16:29:51 GMT+0900 (Japan Standard Time)] nonUsePromiseAll, second: 3
[Thu Jun 29 2023 16:29:55 GMT+0900 (Japan Standard Time)] nonUsePromiseAll, second: 4
[Thu Jun 29 2023 16:30:00 GMT+0900 (Japan Standard Time)] nonUsePromiseAll, second: 5
[Thu Jun 29 2023 16:30:00 GMT+0900 (Japan Standard Time)] nonUsePromiseAll end
------------------
[Thu Jun 29 2023 16:30:00 GMT+0900 (Japan Standard Time)] usePromiseAll start
[Thu Jun 29 2023 16:30:03 GMT+0900 (Japan Standard Time)] usePromiseAll, second: 3
[Thu Jun 29 2023 16:30:04 GMT+0900 (Japan Standard Time)] usePromiseAll, second: 4
[Thu Jun 29 2023 16:30:05 GMT+0900 (Japan Standard Time)] usePromiseAll, second: 5
[Thu Jun 29 2023 16:30:05 GMT+0900 (Japan Standard Time)] usePromiseAll end

直列実行は12秒かかるけど、Promise.allを使うと並列実行になって5秒で終わる

実行イメージはこんな感じ
image.png

結論

非同期処理において直列実行の必要性が無い場合はPromise.allを積極的に使うといいかも

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?