Skip to content

Instantly share code, notes, and snippets.

@jaawerth
Last active September 4, 2018 21:07
Show Gist options
  • Save jaawerth/4bcc85f88cfa97d5d4b8 to your computer and use it in GitHub Desktop.
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.
'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);
// 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