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 asyncFn to each element of array.
  • At most concurrency calls run simultaneously.
  • Return results in the original order.
  • If asyncFn throws for any element, reject immediately.

Example

const results = await mapAsync([1, 2, 3], async (x) => x * 2, 2);
// [2, 4, 6]
Hints (5)
  1. Create a pool of "worker" async functions, each pulling from a shared index.
  2. Each worker increments the index and processes one item at a time.
  3. Store results at the original index for order preservation.
  4. Use Promise.all to wait for all workers to finish.
  5. Start min(concurrency, array.length) workers.

Topics

  • Promises & Async

Asked at

Meta · Google · Stripe · Shopify

Join Us
blur