JavaScript
Promise.all Concurrency Control
A Promise executor with concurrency limit.
By EZ4Code Team
promiseconcurrencyasync
Code
async function pool(tasks, limit) {
const results = [];
const executing = new Set();
for (const task of tasks) {
const p = Promise.resolve().then(() => task());
results.push(p);
executing.add(p);
p.finally(() => executing.delete(p));
if (executing.size >= limit) {
await Promise.race(executing);
}
}
return Promise.all(results);
}Explanation
Controls maximum concurrency via Promise.race, suitable for batch request scenarios.
More JavaScript Snippets
Array Map Filter Reduce
Chain map, filter, reduce, find, some, and every on arrays.
Array Deduplication
Deduplicate an array using Set.
Deep Clone
Deep clone objects, supporting common data types.
Debounce Function
Wait a period of time after an event triggers before executing; reset the timer if triggered again during the wait.
Throttle Function
Limit a function to execute at most once within a time interval.
async/await Error Handling
Wrap async functions to uniformly catch exceptions.