JavaScript数组.reduce与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
<$ em>
我知道你可以利用 Promise.all
使用异步循环,但这是否适用于 .reduce()
?
I know you can utilise Promise.all
with async loops, but does that apply to .reduce()
?
推荐答案
问题是你的累加器值是承诺 - 它们的返回值是 async functi上
秒。为了获得顺序评估(除了最后一次迭代之外的所有迭代),你需要使用
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与async / await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!