DEV Community

Rik Browning
Rik Browning

Posted on

Javscript Async Reduce

Array.reduce is a pretty powerful function but I wanted to share a technique that I have found useful, serial execution of async functions.

const asyncs = [asyncFn, asyncFn1, asyncFn2, ...];

//Simple execution with no results
await asyncs.reduce((promise, asyncFn) => promise.then(asyncFn),
  Promise.resolve());

//Save results to an array
const asyncResults = await asyncs.reduce((promise, asyncFn) => 
  promise.then(results =>
    asyncFn()
      .then(newResult => [...results, newResult])), 
  Promise.resolve([]));

Hope you found this helpful. If you got any other reduce use cases please let me know by leaving a comment.

Top comments (0)