我正在尝试等待async.eachLimit完成,然后再继续。
我的代码:
await async.eachLimit(myList, async (item)=>{
await processItem(item)
})
console.log("all done");
但是我总是在处理完所有事情之前就完成了所有工作。我怎么了?
答案 0 :(得分:0)
您可以尝试Promise.all()
,它返回一个仅在列表中的所有承诺都得到解决时才解决的承诺。
await Promise.all(myList);
console.log("done");
答案 1 :(得分:0)
也许您可以根据需要进行调整(使用1000代替Math.random ..可以更快地运行示例)。
const test = async () => {
const list = [ 1, 2, 3 ]
const testFunc = async (item) => {
return new Promise( ( res, rej ) => {
setTimeout( () => {
console.log(item)
res( true )
}, 1000)
} )
}
await Promise.all( list.map( async ( item ) => {
await testFunc( item )
} ) )
console.log("all done")
}
test()
答案 2 :(得分:0)
我最终像这样解决了它:
await new Promise( (resolve, reject)=>{
async.eachLimit(myList, async (item)=>{
await processItem(item)
}, (err)=> {
if(err) reject(err)
else resolve()
})
问题是由于某种原因,async.eachLimit没有返回可等待的承诺。