Created
April 23, 2024 17:44
-
-
Save RyKilleen/096b2abdaacea08dc4f4f8c010c3e579 to your computer and use it in GitHub Desktop.
Snippet: async batch promise tasks
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
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