Last active
March 22, 2019 20:03
-
-
Save isaaclyman/8b28caed89d50d13ac2f3866ff1bf88a to your computer and use it in GitHub Desktop.
Accept an array of functions that each return a Promise and execute them in order, waiting for each returned Promise to resolve before continuing to the next function
This file contains hidden or 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 orderPromises (promiseFns) { | |
if (!Array.isArray(promiseFns) || (promiseFns.length && typeof promiseFns[0] !== 'function')) { | |
throw new TypeError('orderPromises expects an array of functions. Received: ' + JSON.stringify(promiseFns)) | |
} | |
if (!promiseFns.length) { | |
return Promise.resolve() | |
} | |
const promise = promiseFns[0]() | |
if (!promise.then) { | |
throw new TypeError('A function in the array passed to orderPromises did not return a promise. Returned: ' + JSON.stringify(promise)) | |
} | |
return promise.then(function () { | |
return orderPromises(promiseFns.slice(1)) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment