Created
January 15, 2020 23:06
-
-
Save markreid/0803b86fdff0476f21ee1de85155d1ac to your computer and use it in GitHub Desktop.
run async functions sequentially via reduce
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
/** | |
* 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