Skip to content

Instantly share code, notes, and snippets.

Created February 17, 2022 19:12
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jed/ee9125feec83bb6d9120be48dc976eb8 to your computer and use it in GitHub Desktop.
// per
// "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
for (let p of promises) p.then(write)
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) {
function end() {
done = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment