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

2 comments:

  1. The article provides a concise introduction to implementing a reduction operation over an iterable containing both Promise and non-Promise values. The promiseReduce() function presents a useful approach for combining asynchronous values with the familiar reduce pattern.

    Working with Promise-based reductions is particularly relevant when multiple asynchronous operations need to be processed in sequence while maintaining an accumulated result. The example provides a useful foundation for understanding how Promise handling can be combined with functional programming techniques in JavaScript.

    These concepts are valuable for learners strengthening their understanding of asynchronous programming and modern JavaScript patterns through Javascript Course in Chennai.

    ReplyDelete
  2. The topic also provides practical context for developers progressing through Javascript Training in Chennai, particularly when working with Promise-based application logic.

    ReplyDelete