Skip to content

Instantly share code, notes, and snippets.

@isaaclyman
Last active March 22, 2019 20:03
Show Gist options
  • Save isaaclyman/8b28caed89d50d13ac2f3866ff1bf88a to your computer and use it in GitHub Desktop.
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
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