async-await内で並列的に実行したい場合
function sleepAndSay(time: number, msg: string): Promise<void> {
return new Promise<void>(resolve => {
setTimeout(() => {
console.log(msg)
resolve();
}, time);
});
}
async function main() {
await sleepAndSay(200, 'test1')
await sleepAndSay(100, 'test2')
await Promise.all([
(async () => {
await sleepAndSay(50, 'in promise.all 1-1');
await sleepAndSay(40, 'in promise.all 1-2');
await sleepAndSay(40, 'in promise.all 1-3');
return;
})(),
(async () => {
await sleepAndSay(30, 'in promise.all 2-1');
await sleepAndSay(20, 'in promise.all 2-2');
await sleepAndSay(20, 'in promise.all 2-3');
return;
})(),
])
await sleepAndSay(100, 'test3')
}
実行結果
test1
test2
in promise.all 2-1
in promise.all 1-1
in promise.all 2-2
in promise.all 2-3
in promise.all 1-2
in promise.all 1-3
test3
目的通り動くけどPromise.allはpromiseを受け取る。
async はpromiseを 返す 関数を作るので all内で実行する必要があり、(
が少しうざい。
改善案としてpararels関数を作る
function pararels(...promises: (() => Promise<any>)[]) {
return Promise.all(promises.map(p => p()));
}
async function main2() {
await sleepAndSay(200, 'test1')
await sleepAndSay(100, 'test2')
await pararels(
async () => {
await sleepAndSay(50, 'in promise.all 1-1');
await sleepAndSay(40, 'in promise.all 1-2');
await sleepAndSay(40, 'in promise.all 1-3');
return;
},
async () => {
await sleepAndSay(30, 'in promise.all 2-1');
await sleepAndSay(20, 'in promise.all 2-2');
await sleepAndSay(20, 'in promise.all 2-3');
return;
},
)
await sleepAndSay(100, 'test3')
}
実行結果
test1
test2
in promise.all 2-1
in promise.all 1-1
in promise.all 2-2
in promise.all 2-3
in promise.all 1-2
in promise.all 1-3
test3
少し楽になった