Created
November 9, 2017 00:09
-
-
Save raineorshine/ed3a586700315e566187402c2f4c83d7 to your computer and use it in GitHub Desktop.
accumulate(): 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, 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