【发布时间】:2026-02-17 14:45:01
【问题描述】:
如何使用 Promises 编写同步循环?下面的两个函数都没有等待前一个循环完成后再开始......
(async ()=> {
let arr = [3,1,2,1,2];
const waitFor = ms => new Promise(r => setTimeout(r, ms));
// Using Promise.all
const firstFn = async () => { // doens't work
return Promise.all(arr.map(async (sec) => {
await waitFor(sec*1000);
console.log(`waited for ${sec} seconds`);
}));
}
await firstFn();
// Using new Promise
const secondFn = async () => {
arr.map(sec => {
new Promise(async (res, rej) => {
await waitFor(sec*1000);
console.log(`waited for ${sec} seconds`);
res();
});
});
}
await Promise.all(secondFn());
})();
【问题讨论】:
-
secondFn ()中没有return,map()中的任何一个都没有return -
看到你在使用
async / await使用for (let sec of arr) {。数组函数不支持异步.. -
您不能编写基于 Promise 的同步循环。不过,您可以编写一个异步的顺序循环。
标签: javascript asynchronous promise async-await