Skip to content

Instantly share code, notes, and snippets.

@kettanaito
Last active June 20, 2017 15:08
Show Gist options
  • Save kettanaito/4bcdfe20190cc61cca859a1c9d791719 to your computer and use it in GitHub Desktop.
Save kettanaito/4bcdfe20190cc61cca859a1c9d791719 to your computer and use it in GitHub Desktop.
/**
* Promise sequence
* @description Handles the sequence of Promise.
* @param {Array<Function: Promise>} promises Collection of functions which should return instance of Promise.
* @return {Promise}
*/
function PromiseSeq(promises) {
return promises.reduce((promisesPool, promise) =>
promisesPool.then((result) => {
/* Explicitly check if function (returning promise), since you can pass {true} to it
* to be resolved instantly (conditional Promise). */
const isFunction = (currentPromise instanceof Function);
const appendResult = () => Array.prototype.concat.bind(result);
return isFunction ? currentPromise().then(appendResult()) : appendResult();
}), Promise.resolve([]));
}
}
/**
* Usage example
*/
const promise1 = () => Promise(resolve => setTimeout(() => {
console.log('promise 1 is resolved');
resolve();
}, 3000));
const promise2 = () => Promise(resolve => setTimeout(() => {
console.log('promise 2 is resolved');
resolve();
}, 1500));
PromiseSeq([promise1, promise2]).then(() => {
console.log('All promises have been resolved sequentially!');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment