我有两个代码片段(并行和串行),用reduce在数组上执行一个简单的异步函数。我不明白为什么执行要等到调用Promise.all才开始。这是最好的方法吗?
// Function returning promise with root value
async function proot(x) {
return new Promise((res,rej)=>{
setTimeout( () => {
console.log(x*x);
res(x*x)
},1000)
})
}
// Parallel Execution
var arr1 = [2,3,4].reduce((prev,next)=>{
return prev.concat(proot(next))
},[])
arr1 = await Promise.all(arr1)
// Sequential Execution
var arr2 = [2,3,4].reduce( async (prev,next)=>{
return (await prev).concat(await proot(next))
},Promise.resolve([]))
arr2 = await Promise.all([arr2])