Seem to be having some issues incorporating async/await with .reduce(), like so:
JavaScript
x
18
18
1
const data = await bodies.reduce(async(accum, current, index) => {
2
const methodName = methods[index]
3
const method = this[methodName]
4
if (methodName == 'foo') {
5
current.cover = await this.store(current.cover, id)
6
console.log(current)
7
return {
8
accum,
9
current
10
}
11
}
12
return {
13
accum,
14
method(current.data)
15
}
16
}, {})
17
console.log(data)
18
The data
object is logged before the this.store
completes…
I know you can utilise Promise.all
with async loops, but does that apply to .reduce()
?
Advertisement
Answer
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
JavaScript
1
5
1
const data = await array.reduce(async (accumP, current, index) => {
2
const accum = await accumP;
3
…
4
}, Promise.resolve(…));
5
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.