Skip to content

Instantly share code, notes, and snippets.

@townofdon
Created October 11, 2021 15:58
Show Gist options
  • Save townofdon/7e1396f0daa8002228c49695b0f01136 to your computer and use it in GitHub Desktop.
Save townofdon/7e1396f0daa8002228c49695b0f01136 to your computer and use it in GitHub Desktop.
Execute Promises in Sequence
/**
* executePromisesInSequence
*
* Given an array of functions, each of which return a Promise,
* fire off each promise in sequence, one after the other.
*
* @param {func[]} promises
* @returns {Promise}
*/
module.exports = function executePromisesInSequence(promises, {
willCatchErrors = true,
} = {}) {
const successes = [];
const errors = [];
const onReduce = (promiseChain, currentTask) => {
if (!promiseChain.then) {
return Promise.resolve();
}
return promiseChain.then(() => {
if (typeof currentTask !== 'function') {
return Promise.resolve();
}
const invoked = currentTask();
if (!invoked.then) {
return Promise.resolve();
}
const executedPromise = invoked.then((currentResult) => {
successes.push(currentResult);
});
if (willCatchErrors) {
return executedPromise.catch((err) => {
errors.push(err);
});
}
return executedPromise;
});
};
return promises
.reduce(onReduce, Promise.resolve())
.then(() => ({
successes,
errors,
}));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment