Skip to main content

promiseReduce

// promiseReduce pattern is used to run async tasks sequentially using Array.reduce()
// without it, async operations usually run in parallel with map + Promise all

// Common use cases:

// * rate limiting API calls ==> might need to avoid 429 errors
// * ordered database writes
// * queue processing
// * avoiding concurrent requests
// * async workflows with dependencies
// * retry pipelines

function asyncFunc(e) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(e), e * 1000);
});
}

const arr = [1, 2, 3];
let final = [];

function workMyCollection(arr) {
return arr.reduce((promise, item) => {
return promise
.then((result) => {
console.log(`item ${item}`);
return asyncFunc(item).then(result => final.push(result));
})
.catch(console.error);
}, Promise.resolve());
}

workMyCollection(arr)
.then(() => console.log(`FINAL RESULT is ${final}`));


// Cleaner versio is for - of

async function workMyCollection(arr) {
const final = [];

// this loop will be run in sequential, not in parallel
for (const item of arr) {
console.log(`item ${item}`);
const result = await asyncFunc(item);
final.push(result);
}

return final;
}

workMyCollection(arr)
.then((result) => {
console.log(`FINAL RESULT is ${result}`);
});