Created
August 7, 2016 15:37
-
-
Save madox2/c3d7072b515ab293f2bd2cedbb4b09d2 to your computer and use it in GitHub Desktop.
run asynchronous tasks sequentially
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
/** | |
* Returns promise which runs given callback functions in series and | |
* collect results in array. | |
* | |
* @param {array} promises - array of callback functions | |
*/ | |
function promiseAllSeq(promises) { | |
var data = []; | |
return promises.reduce((p, fn) => p.then(fn).then(i => (data.push(i), data)), Promise.resolve()); | |
} | |
const p = [ | |
() => new Promise(resolve => setTimeout(() => { | |
return resolve('Hello') | |
}, 100)), | |
() => Promise.resolve('world'), | |
() => new Promise(resolve => setTimeout(() => { | |
return resolve('!') | |
}, 50)) | |
]; | |
promiseAllSeq(p).then(results => console.log(results)); // [ 'Hello', 'world', '!' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment