Created
April 22, 2025 10:55
-
-
Save lewxdev/6e79480f4fe7afa13effed4fc3898df6 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
| export const batchAsync = async function <T>( | |
| iterable: Iterable<T> | AsyncIterable<T>, | |
| callback: (value: T) => Promise<void>, | |
| limit: number, | |
| ) { | |
| const batch = new Set<Promise<void>>(); | |
| for await (const value of iterable) { | |
| const promise = callback(value).finally(() => { | |
| batch.delete(promise); | |
| }); | |
| batch.add(promise); | |
| if (batch.size >= limit) { | |
| await Promise.race(batch); | |
| } | |
| } | |
| await Promise.all(batch); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment