async function pLimit(tasks, limit = 5) {
const results = [];
const executing = new Set();
for (const task of tasks) {
const p = Promise.resolve().then(task).then((r) => {
executing.delete(p);
return r;
});
executing.add(p);
results.push(p);
if (executing.size >= limit) {
await Promise.race(executing);
}
}
return Promise.all(results);
}
// Usage
const urls = Array.from({ length: 20 }, (_, i) => `/api/item/${i}`);
const tasks = urls.map((url) => () => fetch(url).then((r) => r.json()));
const data = await pLimit(tasks, 4); // max 4 concurrent
Create a free account and build your private vault. Share publicly whenever you want.