Async Map with Concurrency
MediumPromises & Async20 min5 tests
Implement mapAsync(array, asyncFn, concurrency) that maps over an array with an async function, limiting concurrency.
Requirements
- Apply
asyncFnto each element ofarray. - At most
concurrencycalls run simultaneously. - Return results in the original order.
- If
asyncFnthrows for any element, reject immediately.
Example
const results = await mapAsync([1, 2, 3], async (x) => x * 2, 2);
// [2, 4, 6]Hints (5)
- Create a pool of "worker" async functions, each pulling from a shared index.
- Each worker increments the index and processes one item at a time.
- Store results at the original index for order preservation.
- Use Promise.all to wait for all workers to finish.
- Start min(concurrency, array.length) workers.
Topics
- Promises & Async
Asked at
Meta · Google · Stripe · Shopify
