Skip to content

Instantly share code, notes, and snippets.

@raineorshine
Last active April 6, 2017 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raineorshine/5962bd6f260c0475edf98db9afe485c7 to your computer and use it in GitHub Desktop.
Save raineorshine/5962bd6f260c0475edf98db9afe485c7 to your computer and use it in GitHub Desktop.
Executes an array of promises or promise-returning functions serially and reduces the results with the given accumulator.
const waterfall = require('promise.waterfall')
const Bluebird = require('bluebird')
const _ = require('lodash')
// an array of 10ms functions with different return values
const functions = [
() => Bluebird.delay(10, 'a'),
() => Bluebird.delay(10, 'b'),
() => Bluebird.delay(10, 'c')
]
/** Executes an array of promises or promise-returning functions serially and reduces thes results with the given accumulator */
function promiseReduce(functionsOrPromises, accumulator, start) {
return waterfall(functionsOrPromises.map((o, i) => {
const p = typeof o === 'function' ? o() : o
return acc => p.then(result => accumulator(i === 0 ? start : acc, result))
}))
}
/** Executes an array of promises or promise-returning functions serially and returns an array of the results. */
function accumulate(functions) {
return promiseReduce(functions, _.concat, [])
}
accumulate(functions)
.then(console.log)
.catch(console.error)
// can be done more directly, albeit a little more complex
functions.reduce((accPromise, f) =>
f().then(result =>
accPromise.then(acc => acc.concat(result))
), Promise.resolve([])
)
.then(console.log)
.catch(console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment