Last active
July 31, 2017 23:06
-
-
Save jesuscast/d7b9d0a29dd921e03d932c117eeba8ce to your computer and use it in GitHub Desktop.
Simple Utility to resolve an array of promises in series.
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
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