Skip to content

Instantly share code, notes, and snippets.

@john-doherty
Last active March 11, 2023 19:20
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 john-doherty/c6d79cd4924c0f9bd2449c48231b2108 to your computer and use it in GitHub Desktop.
Save john-doherty/c6d79cd4924c0f9bd2449c48231b2108 to your computer and use it in GitHub Desktop.
Similar to Promise.all but executes promises in sequence
/**
* 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);
});
}
@john-doherty
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment