Problem Statement
Implement an asynchronous function mapAsyncLimit that applies a callback function to each element of an iterable, limiting how many promises run concurrently.
Unlike batch-based processing, this version should start a new task as soon as one finishes, maintaining a constant concurrency level until all items are processed.
The function must:
- Support asynchronous callbacks.
- Limit the number of concurrent tasks to a specified
size. - Preserve the order of results.
- Reject immediately if any callback throws an error.
- Resolve to an empty array if the input iterable is empty.
Example
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const result = await mapAsyncLimit(
[1, 2, 3, 4, 5],
async (num) => {
await delay(100);
return num * 2;
},
2
);
console.log(result); // [2, 4, 6, 8, 10]
Constraints
iterablemust be an array.callbackFnmust return a Promise.sizemust be a positive integer (default:Infinity).