Last active
March 11, 2023 19:20
-
-
Save john-doherty/c6d79cd4924c0f9bd2449c48231b2108 to your computer and use it in GitHub Desktop.
Similar to Promise.all but executes 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
/** | |
* Executes an array of functions that return a promise in sequence | |
* @example | |
* promisesInSequence([ | |
* function() { return Promise.resolve(1); } | |
* function() { return Promise.resolve(2); }, | |
* function() { return Promise.resolve(3); } | |
* ]) | |
* .then(function(result) { | |
* console.log(result.join(',')); // output = 1,2,3 | |
* }); | |
* @param {Array<function>} promises - array of functions that return a promise | |
* @returns {Promise} executes .then if all resolve otherwise .catch | |
*/ | |
function promisesInSequence(promises) { | |
var result = Promise.resolve(); | |
var items = []; | |
promises.forEach(function (promise) { | |
result = result.then(promise).then(function(item) { | |
items.push(item); | |
return Promise.resolve(); | |
}); | |
}); | |
return result.then(function() { | |
return Promise.resolve(items); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
Output
1,2,3