今天在做一个模拟队列任务执行的功能的时候,发现使用await不能使用foreach,后来发现使用for...of或者for语句就能解决这个问题。
一、使用forEach的代码
let func = (num) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('执行数据' + num)
}, 1000);
})
}
async function test() {
[1, 2, 3, 4, 5, 6, 7].forEach((item, index) => {
let ret = await func(item);
console.log(ret);
});
}
test();
结果
二、使用for...of或者for语句
let func = (num) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('执行数据' + num)
}, 1000);
})
}
async function test() {
//for...of
for (const item of [1, 2, 3, 4, 5, 6, 7]) {
let ret = await func(item);
console.log(ret);
}
//for
for (let index = 0; index < [1, 2, 3, 4, 5, 6, 7].length; index++) {
let ret = await func(index);
console.log(ret);
}
}
test();
结果
网友评论