Skip to content

Instantly share code, notes, and snippets.

@RyKilleen
Created April 23, 2024 17:44
Show Gist options
  • Save RyKilleen/096b2abdaacea08dc4f4f8c010c3e579 to your computer and use it in GitHub Desktop.
Save RyKilleen/096b2abdaacea08dc4f4f8c010c3e579 to your computer and use it in GitHub Desktop.
Snippet: async batch promise tasks
async function* asyncBatchGenerator<T>(
tasks: (() => Promise<T>)[],
batchSize: number
): AsyncGenerator<PromiseSettledResult<T>[]> {
for (let i = 0; i < tasks.length; i += batchSize) {
const batchTasks = tasks.slice(i, i + batchSize);
const batchPromises = batchTasks.map((task) => task());
yield Promise.allSettled(batchPromises);
}
}
// Usage
const batchProcessStuff = () => {
const batchSize = 2;
const tasks = [
() => someAsyncTask(),
() => someAsyncTask(),
() => someAsyncTask()
]
const responses: PromiseSettledResult<ZoneResult | undefined>[][] = [];
for await (const batch of asyncBatchGenerator(tasks, batchSize)) {
responses.push(batch);
}
return responses.flat();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment