JavaScript 数组 .reduce with async/await [英] JavaScript array .reduce with async/await
问题描述
似乎在将 async/await 与 .reduce() 合并时遇到了一些问题,如下所示:
Seem to be having some issues incorporating async/await with .reduce(), like so:
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
完成之前被记录...
The data
object is logged before the this.store
completes...
我知道您可以将 Promise.all
与异步循环一起使用,但这是否适用于 .reduce()
?
I know you can utilise Promise.all
with async loops, but does that apply to .reduce()
?
推荐答案
问题是您的累加器值是承诺 - 它们是 async function
的返回值.要获得顺序评估(以及所有等待的最后一次迭代),您需要使用
The problem is that your accumulator values are promises - they're return values of async function
s. To get sequential evaluation (and all but the last iteration to be awaited at all), you need to use
const data = await array.reduce(async (accumP, current, index) => {
const accum = await accumP;
…
}, Promise.resolve(…));
也就是说,对于async
/await
,我通常会推荐使用普通循环代替数组迭代方法,它们的性能更高且通常更简单.
That said, for async
/await
I would in general recommend to use plain loops instead of array iteration methods, they're more performant and often simpler.
这篇关于JavaScript 数组 .reduce with async/await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!