Problem Statement

When working with asynchronous operations over large datasets (like fetching data from APIs or reading files), executing all promises at once can overwhelm the system or the network.
To manage concurrency efficiently, developers use a map with concurrency limit, where only a fixed number of promises run simultaneously, and new ones start only when one batch finishes.

In this challenge, you’ll implement a simplified version of that — a utility that processes items asynchronously in batches.


Your Task

Implement a function mapAsyncLimit(iterable, callbackFn, size) that:

  • Takes an iterable (such as an array).
  • Applies the asynchronous callbackFn to each item.
  • Processes items in parallel batches of the specified size.
  • Waits for each batch to complete before starting the next.
  • Returns an array of all results in the original order.

Example

const delayDouble = async (n) => {
await new Promise((r) => setTimeout(r, 100));
return n * 2;
};

const arr = [1, 2, 3, 4, 5, 6];

const result = await mapAsyncLimit(arr, delayDouble, 2);
console.log(result);


Expected Output:

[2, 4, 6, 8, 10, 12]


Explanation:

  • Only two promises run at a time (size = 2).
  • When both complete, the next two start.

Expected Behavior

  • Processes asynchronous tasks in parallel batches.
  • Preserves the original order of results.
  • Starts a new batch only after the previous one completes.

Hints

Hint 1

Use Promise.all() to wait for a batch of promises.

Hint 2

Use array slicing to create batches.

Hint 3

Collect results into a single array before returning.