Batch Async Processing
MediumPromises & Async15 min5 tests
Implement batchAsync(items, batchSize, asyncFn) that processes items in sequential batches.
Requirements
- Split
itemsinto batches ofbatchSize. - Within each batch, run all items in parallel via
asyncFn(item). - Batches are sequential: batch 2 starts only after batch 1 completes.
- Return a flat array of all results in the original order.
Example
const results = await batchAsync(
[1, 2, 3, 4, 5],
2,
async (x) => x * 10
);
// [10, 20, 30, 40, 50]Hints (4)
- Use a for loop stepping by batchSize to create batches with slice.
- For each batch, use Promise.all to run all items in parallel.
- Await the Promise.all before moving to the next batch.
- Collect all results with spread or concat.
Topics
- Promises & Async
Asked at
Amazon · Shopify · Stripe
