はじめに
非同期処理を複数回実行する時は、直列で実行するより並列で実行する方が早く終わるよ、という話
処理によっては直列で実行しないといけない場合はあると思うけど、その必要性が無い場合は並列実行する方が処理速度の恩恵を受けれる。
プログラム
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秒で終わる
結論
非同期処理において直列実行の必要性が無い場合はPromise.all
を積極的に使うといいかも