Skip to content

Instantly share code, notes, and snippets.

@markreid
Created January 15, 2020 23:06
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save markreid/0803b86fdff0476f21ee1de85155d1ac to your computer and use it in GitHub Desktop.
Save markreid/0803b86fdff0476f21ee1de85155d1ac to your computer and use it in GitHub Desktop.
run async functions sequentially via reduce
/**
* Run a series of async/promisifed functions sequentially,
* returning an array of results and errors.
*
* example:
* const values = [1, 2, 3, 4, 5];
* const callback = async (value) => await someAsyncThing(value)
* const result = await sequentialAsync(values, callback);
*
* @param {Iterable} values
* @param {Function} callback
* @return {Object} object with .result and .errors arrays
*/
const sequentialAsync = (values, callback) => values.reduce(async (acc, value) => {
const resultsObject = await acc;
try {
const result = await callback(value);
return {
...resultsObject,
results: [...resultsObject.results, result],
};
} catch (error) {
return {
...resultsObject,
errors: [...resultsObject.errors, error],
};
}
}, Promise.resolve({
results: [],
errors: [],
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment