Skip to content

Instantly share code, notes, and snippets.

@timvandam
Created February 1, 2021 11:38
Show Gist options
  • Save timvandam/76c145eccf5c9de026be24c2cc1ce364 to your computer and use it in GitHub Desktop.
Save timvandam/76c145eccf5c9de026be24c2cc1ce364 to your computer and use it in GitHub Desktop.
Promise Iterator
/**
* Yields promises as they settle.
* @param promises List of promise to yield through
*/
export default async function* PromiseIterator<P>(promises: Iterable<Promise<P>>): AsyncGenerator<[Promise<P>], void, void> {
const pending = new Set<Promise<P>>(promises)
const settled = new Set<Promise<P>>()
// Move pending promises to `settled` when they settle
pending.forEach((promise) =>
promise
.catch(() => void 0)
.finally(() => {
pending.delete(promise)
settled.add(promise)
})
)
// Yield promises as they settle, until all promises have been yielded
while (pending.size || settled.size) {
await Promise.race([Promise.race(settled), Promise.race(pending)]).catch(() => void 0)
for (const result of settled) {
settled.delete(result)
yield [result]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment