Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// per https://twitter.com/yoshuawuyts/status/1494119486429007879
// "In JavaScript, is there a function which takes N Promises, and returns an asyncIterator which yields N resolved values?"
let promises = Array.from({length: 10}, (n, i) => {
return new Promise(cb => setTimeout(cb, Math.random() * 1e3, i))
})
let iterator = iteratePromises(promises)
for await (let value of iterator) console.log(value)
function iteratePromises(promises) {
let done = false
let queue = []
let resolve
let promise
defer()
for (let p of promises) p.then(write)
Promise.all(promises).then(end)
return read()
function defer() {
promise = new Promise(r => resolve = r)
}
async function* read() {
await promise
yield* queue.splice(0)
if (!done) yield* read()
}
function write(value) {
queue.push(value)
resolve()
defer()
}
function end() {
done = true
resolve()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment