HomePremium · ₹1199
← All questions

mapLimit: async map with a concurrency limit

Medium
Asked at:UberSwiggy
Was this asked in an interview?

Run an async mapper over an array with at most N calls in flight, preserving output order.

Problem

You have 500 image URLs to process, but firing 500 requests at once will exhaust sockets and trip rate limits. You want to process them N at a time — start the next as soon as one finishes — while still getting results back in the original order.

Implement mapLimit(inputs, limit, iteratee) that:

  • Calls iteratee(input) (returns a promise) for each input.
  • Keeps at most limit calls in flight at any moment.
  • Resolves with an array of results in input order.
  • Rejects if any iteratee rejects.

Input

const asyncDouble = (n) =>
  new Promise((res) => setTimeout(() => res(n * 2), 100));

mapLimit([1, 2, 3, 4, 5], 2, asyncDouble).then(console.log);

Expected output

  • [2, 4, 6, 8, 10] — with never more than 2 running at once.

Implement from scratch:

function mapLimit(inputs, limit, iteratee) {
  // Your code here
}
mapLimit: async map with a concurrency limit — JavaScript Interview Question | Mentoxis