Last active
June 20, 2017 15:08
-
-
Save kettanaito/4bcdfe20190cc61cca859a1c9d791719 to your computer and use it in GitHub Desktop.
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
/** | |
* 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