Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
accumulate(): 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, acculumator, start) {
return waterfall(functionsOrPromises.map((o, i) => {
const p = typeof o === 'function' ? o() : o
return acc => p.then(result => acculumator(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
You can’t perform that action at this time.