Skip to content

Instantly share code, notes, and snippets.

@lewxdev
Created April 22, 2025 10:55
Show Gist options
  • Select an option

  • Save lewxdev/6e79480f4fe7afa13effed4fc3898df6 to your computer and use it in GitHub Desktop.

Select an option

Save lewxdev/6e79480f4fe7afa13effed4fc3898df6 to your computer and use it in GitHub Desktop.
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