Skip to main content

Pattern using reduce() to process array of promises and collect results

This is a pattern using Array.prototype.reduce() to iterate over an array of promises using async/await AND collect the results.

// generate an array of promises (simulation with short random delays)
let arr = Array.from(Array(6).keys())
.map(i => new Promise((resolve, reject) =>
setTimeout(
() => resolve({i, val: Math.random()*5000}),
Math.random()*5000)
))

;(async () => {
let newArr
await arr.reduce(async (prev, curr, i) => {
const collection = await prev
console.log(`processing ${i+1} ...`)
collection.push(await curr)
return collection
}, Promise.resolve([]))
.then(data => { // do something with the data collected
//console.log({data})
newArr = [...data]
})
console.log('data collected', {newArr})
})()

will output something like this:

processing 1 ...
processing 2 ...
processing 3 ...
processing 4 ...
processing 5 ...
processing 6 ...
data collected {
newArr: [
{ i: 0, val: 1431.309469650781 },
{ i: 1, val: 359.8259485548982 },
{ i: 2, val: 1441.3047903330435 },
{ i: 3, val: 4105.878962978907 },
{ i: 4, val: 4077.296532717496 },
{ i: 5, val: 3530.631526198138 }
]
}