Back to Async / PromisesMedium
Exercise 17: Promise Map (transform array)
Problem Statement
Function `promiseMap(arr, fn, concurrency)` banao jo array ko promise function se map kare with concurrency.
Example: promiseMap([1,2,3], async (x) => x*2, 2)
Sample Output:
await promiseMap([1,2,3], async (x) => x*2, 2) => [2, 4, 6] // Maps with max 2 concurrent
Solution
const promiseMap = async (arr, fn, concurrency = Infinity) => {
const results = [];
for (let i = 0; i < arr.length; i += concurrency) {
const batch = arr.slice(i, i + concurrency);
results.push(...await Promise.all(batch.map(fn)));
}
return results;
};Explanation
Overall Goal:
- Array ko async function se map karna with concurrency.
Real world:
- Data transformation: async mapping.
- API calls: batch processing.