Created
October 11, 2021 15:58
-
-
Save townofdon/7e1396f0daa8002228c49695b0f01136 to your computer and use it in GitHub Desktop.
Execute Promises in Sequence
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
/** | |
* 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