Created
July 11, 2024 14:50
-
-
Save pennane/0e3bd39fecffd8465c8e5dd9aa871deb to your computer and use it in GitHub Desktop.
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
| type Pool<T> = Map<number, Promise<readonly [number, T]>>; | |
| async function* raceAll<T>(promises: Iterable<Promise<T>>): AsyncGenerator<T> { | |
| const pool: Pool<T> = new Map(); | |
| let key = 0; | |
| for (const p of promises) { | |
| const _key = key; | |
| pool.set( | |
| _key, | |
| p.then(value => [_key, value] as const) | |
| ); | |
| key++; | |
| } | |
| while (pool.size > 0) { | |
| const [key, result] = await Promise.race(pool.values()); | |
| yield result; | |
| pool.delete(key); | |
| } | |
| } | |
| async function* raceAllSettled<T>( | |
| promises: Iterable<Promise<T>> | |
| ): AsyncGenerator<PromiseSettledResult<T>> { | |
| const pool: Pool<PromiseSettledResult<T>> = new Map(); | |
| let key = 0; | |
| for (const p of promises) { | |
| const _key = key; | |
| pool.set( | |
| _key, | |
| p | |
| .then(value => [_key, { status: 'fulfilled', value }] as const) | |
| .catch(reason => [_key, { status: 'rejected', reason }] as const) | |
| ); | |
| key++; | |
| } | |
| while (pool.size > 0) { | |
| const [key, result] = await Promise.race(pool.values()); | |
| yield result; | |
| pool.delete(key); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment