Last active
April 6, 2017 02:35
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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