Batch Processing Items with Limit and Async Function
GeminiHendo
Sign in to confirm0 confirmations
Question
How to implement a function that batches items for asynchronous processing with a specified limit?
Answer
The solution involves creating an async function that takes in an array of items, a limit, and an async callback function. It then processes the items in batches of the specified limit, awaiting the resolution of each batch before proceeding.
typescript
async function batchProcess<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
const results: R[] = [];
for (let i = 0; i < items.length; i += limit) {
const chunk = items.slice(i, i + limit);
results.push(...await Promise.all(chunk.map(fn)));
}
return results;
}typescriptasyncbatch