Implementing mapAsyncLimit in JavaScript
1. Problem Statement
Implement mapAsyncLimit(iterable, callbackFn, size) to apply an asynchronous callback to every array element while limiting the number of tasks running concurrently.
Requirements:
- Run at most size tasks at a time.
- Preserve the original order of results.
- Reject if any callback rejects.
- If size is omitted, allow unlimited concurrency.
2. Input and Output
Input:
const arr = [10, 20, 30, 40, 50];
const result = await mapAsyncLimit(
arr,
async (n) => n * 2,
2
);
Here, size = 2 means at most two tasks can run concurrently, and the callback doubles each number.
Output:
[20, 40, 60, 80, 100]
3. Solution
export default async function mapAsyncLimit(
iterable,
callbackFn,
size = Infinity
) {
const n = iterable.length;
const result = new Array(n);
let index = 0;
async function worker() {
while (index < n) {
const i = index++;
result[i] = await callbackFn(iterable[i]);
}
}
const workers = Array.from(
{ length: Math.min(size, n) },
() => worker()
);
await Promise.all(workers);
return result;
}
4. How Are Tasks Distributed?
We do not divide the array into fixed chunks. Instead, we create a limited number of workers, and each worker picks the next available item.
For example:
arr = [10, 20, 30, 40, 50];
size = 2;
We create two workers:
- Worker 1 picks 10 (index 0).
- Worker 2 picks 20 (index 1).
- When either worker finishes, it picks the next available item.
- This continues until all items are processed.
The worker that finishes first gets the next item. Neither worker owns a fixed part of the array.
5. Dry Run
Assume each task takes one second to complete.
At 0 seconds:
- Worker 1 picks 10, using index 0.
- Worker 2 picks 20, using index 1.
- The shared index is now 2.
At 1 second:
- Both workers finish their tasks.
- Worker 1 picks 30, using index 2.
- Worker 2 picks 40, using index 3.
- The shared index is now 4.
At 2 seconds:
- Both workers finish again.
- Worker 1 picks 50, using index 4.
- Worker 2 finds that all items have been assigned and stops.
At 3 seconds:
- Worker 1 finishes.
- All workers are done, so the function returns:
[20, 40, 60, 80, 100]
The exact distribution depends on task completion times. If Worker 2 finishes first, Worker 2 gets the next item.
6. How Does a Worker Pick an Item?
The most important line is:
const i = index++;
Suppose index = 0.
const i = index++; // i = 0, index becomes 1
The next worker sees index = 1 and claims index 1.
All workers share the same index, so each worker claims a different item. JavaScript executes index++ synchronously before reaching await.
Next:
result[i] = await callbackFn(iterable[i]);
The worker processes the item and waits for its callback to finish before looping again to claim another item.
Remember: await pauses the current worker, not the entire JavaScript program. Other workers can continue running.
7. Why Do We Need Promise.all()?
const workers = Array.from(
{ length: Math.min(size, n) },
() => worker()
);
await Promise.all(workers);
return result;
- Math.min(size, n) ensures we don't create more workers than items.
- Array.from() starts the workers.
- Promise.all() waits for all workers to finish.
- return result returns the completed array in its original order.
If any callback rejects, Promise.all() rejects with the same reason, and mapAsyncLimit also rejects.
8. Complexity
- Space: O(n + k), where n is the number of items and k is the number of workers.
- Time: Depends on task duration. If all tasks take approximately T time and run in batches of k, execution takes roughly ceil(n / k) × T.
Implementing mapAsyncLimit in JavaScript was originally published in Modern Frontend on Medium, where people are continuing the conversation by highlighting and responding to this story.