Saturday, November 11, 2017

Javascript Promise Reduction

Simple function to perform a reduce on an iterable of Promise/Non-Promise objects.

function promiseReduce (iterable, reducer, initialValue) {
  return iterable.reduce((previousPromise, currentPromise, count) => {
    return Promise.resolve(previousPromise).then(result => {
      return Promise.resolve(currentPromise).then(current => {
        return reducer(result, current, count)
      })
    })
  }, Promise.resolve(initialValue))
}
See fiddle
Or you can use Bluebird.js

No comments:

Post a Comment