配列から呼ぶ非同期関数を直列に実行する命題配列がある時に、ループでその値を利用して非同期関数を呼ぶが、その実行を直列にしたい 解決 async function sleep(time) {
return new Promise((resolve) => { setTimeout(resolve, time) });
}
const times = [3000, 1000, 2000];
void (async () => {
for (t of times) {
console.log(t + " start");
await sleep(t);
console.log(t + " end");
}
})();
🡳 🡳 🡳
3000 start
3000 end
1000 start
1000 end
2000 start
2000 end
map()やPromise.all()を使うと順番通りに完了しない void (async () => {
times.map(async (t) => {
console.log(t + " start");
await sleep(t);
console.log(t + " end");
});
})();
🡳 🡳 🡳
3000 start
1000 start
2000 start
1000 end
2000 end
3000 end
void (() => {
Promise.all(times.map(async (t) => {
console.log(t + " start");
await sleep(t);
console.log(t + " end");
}));
})();
🡳 🡳 🡳
3000 start
1000 start
2000 start
1000 end
2000 end
3000 end
|
|