我该如何使用 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
。 - charlietflasync / await
,请使用for (let sec of arr) {
。数组函数不具备异步感知能力。 - Keith