Created
February 1, 2021 11:38
-
-
Save timvandam/76c145eccf5c9de026be24c2cc1ce364 to your computer and use it in GitHub Desktop.
Promise Iterator
This file contains 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
/** | |
* 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