Map Async Limit
JavaScript
medium
25 mins
Implement a function mapAsyncLimit(arr, limit, asyncFn) that:
- Runs
asyncFnon each item ofarr. - Only runs
limitnumber of async operations concurrently. - Returns a Promise that resolves to an array of results in the same order as input.
Input:
arr: Array of items.limit: Maximum number of concurrent async calls.asyncFn: Asynchronous function returning a promise.
Output:
- A promise that resolves to an array of results after processing all inputs using
asyncFn.
Example Inputs & Outputs
// Example: delayFn = x => new Promise(resolve => setTimeout(() => resolve(x * 2), 100)) await mapAsyncLimit([1, 2, 3, 4], 2, delayFn); // Output: [2, 4, 6, 8] // Example: limit = 1 behaves like sequential map await mapAsyncLimit([1, 2, 3], 1, delayFn); // Output: [2, 4, 6]
Constraints & Edge Cases
arr.lengthcan be 0 → should return an empty array.limitshould be >= 1.asyncFnmay fail → should propagate the error.- Results must maintain input order.
- Should handle non-promise-returning functions gracefully (wrap in
Promise.resolve()if needed).
Companies:
netflix
uber
tcs
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
