似乎在将 async/await 与 .reduce() 合并时遇到了一些问题,如下所示:
const data = await bodies.reduce(async(accum, current, index) => {
const methodName = methods[index]
const method = this[methodName]
if (methodName == 'foo') {
current.cover = await this.store(current.cover, id)
console.log(current)
return {
...accum,
...current
}
}
return {
...accum,
...method(current.data)
}
}, {})
console.log(data)
data
对象在 this.store
完成之前被记录...
我知道您可以将 Promise.all
与异步循环一起使用,但这是否适用于 .reduce()
?
最佳答案
问题是您的累加器值是 promise - 它们是 async function
的返回值。要获得顺序评估(以及除了最后一次迭代之外的所有迭代),您需要使用
const data = await array.reduce(async (accumP, current, index) => {
const accum = await accumP;
…
}, Promise.resolve(…));
也就是说,对于async
/await
,我一般会推荐use plain loops instead of array iteration methods ,它们的性能更高,而且通常更简单。
关于JavaScript 数组 .reduce 和 async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41243468/