Last active
September 4, 2018 21:07
-
-
Save jaawerth/4bcc85f88cfa97d5d4b8 to your computer and use it in GitHub Desktop.
Run a list of functions in series, returning a pjromise that resolves to an array of results.
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
'use strict'; | |
/* | |
* run promises in sequence, return an array of results. | |
* Returns a promise that resolves to an array of results, where funcs[i]() -> results[i] | |
*/ | |
function asyncSeries(...funcs) { | |
return aggregate([], funcs); | |
} | |
function aggregate(results, funcs) { | |
if (funcs.length === 0) return Promise.all(results); | |
return funcs[0]().then(result => aggregate([...results, result], funcs.slice(1))); | |
} | |
// usage (ES6-friendly this time): | |
asyncSeries(fn1, () => fn2(someArg), () => someObj.fn3(someOtherArg), fn4); |
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
// same as above, using reduce | |
function asyncSeries(...funcs) { | |
return funcs.reduce(function execAsyncFuncsInSeries(res, func) { | |
return res.then(results => { | |
return func().then(result => results.concat([result])); | |
}); | |
}, Promise.resolve([])); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment