Skip to content

Instantly share code, notes, and snippets.

@jesuscast
Last active July 31, 2017 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesuscast/d7b9d0a29dd921e03d932c117eeba8ce to your computer and use it in GitHub Desktop.
Save jesuscast/d7b9d0a29dd921e03d932c117eeba8ce to your computer and use it in GitHub Desktop.
Simple Utility to resolve an array of promises in series.
function promiseReducer(arrayOfPromiseHolders, resolve, reject) {
if (arrayOfPromiseHolders.length > 0) {
const promiseHolder = arrayOfPromiseHolders.shift();
promiseHolder().then(() => {
promiseReducer(arrayOfPromiseHolders, resolve, reject);
}).catch((err) => {
reject(err);
});
} else {
resolve();
}
}
/**
* Resolve in series takes an array of functions that return a promise, and then
* resolves them in series
*
* Usage:
* resolveInSeries([
* () => {
* return new Promise((resolve) => { console.log("I will print first!"); resolve(); })
* },
* () => {
* return new Promise((resolve) => { console.log("I will print second!"); resolve(); })
* }
* ]).then(() => {
* console.log("I will print at the end");
* });
*/
function resolveInSeries(arrayOfPromiseHolders) {
return new Promise((resolve, reject) => {
promiseReducer(arrayOfPromiseHolders, resolve, reject);
});
}
export resolveInSeries;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment