Created
February 17, 2022 12:22
-
-
Save reu/d49c9e45138ed6909db5418f20236376 to your computer and use it in GitHub Desktop.
Async iterator that yields each promises results in resolve order
This file contains hidden or 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
async function* promisesIter(promises) { | |
promises = [...promises]; | |
const buffer = []; | |
for (promise of promises) { | |
promise.then(result => { | |
promises.splice(promises.indexOf(promise), 1); | |
buffer.push(result); | |
}); | |
} | |
while (promises.length === 0 || await Promise.race(promises).then(() => true)) { | |
while (buffer.length > 0) yield buffer.pop(); | |
if (promises.length === 0) break; | |
await new Promise(res => setTimeout(res, 0)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@reu I found a couple things that needed changing:
I’ve updated my gist with more detail, and I promise to stop bugging you.