Created
May 5, 2017 15:08
-
-
Save GianlucaGuarini/fd47c3eb29b0d78ed1c918a40e1ea70b to your computer and use it in GitHub Desktop.
Run promises as 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
function sequence(promises) { | |
return new Promise((resolve, reject) => { | |
const rets = [] | |
const gen = (function*() { | |
// loop as long as we have promises in the queue | |
while (promises.length) { | |
// take always the first promise | |
const promise = promises.shift() | |
// wait until it's resolved to step to the next iteration | |
promise | |
.then(gen.next.bind(gen)) | |
.catch(reject) | |
// push the result to the return values | |
rets.push(yield) | |
} | |
// resolve the promise with all the returned values if everything went fine | |
resolve(rets) | |
})() | |
// kick the generator | |
gen.next() | |
}) | |
} | |
sequence([ | |
new Promise(r => setTimeout(r, 2000, 'ciao')), | |
new Promise(r => setTimeout(r, 1000, 'bello')), | |
]).then(console.log).catch(console.log) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment