Skip to content

Instantly share code, notes, and snippets.

@GianlucaGuarini
Created May 5, 2017 15:08
Show Gist options
  • Save GianlucaGuarini/fd47c3eb29b0d78ed1c918a40e1ea70b to your computer and use it in GitHub Desktop.
Save GianlucaGuarini/fd47c3eb29b0d78ed1c918a40e1ea70b to your computer and use it in GitHub Desktop.
Run promises as sequence
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