P-Limit Concurrency Control for Task Queues
Cap parallel task execution with p-limit so large batches of promises run at a fixed concurrency instead of exhausting memory or API quotas.
Code
import pLimit from 'p-limit';
const limit = pLimit(4);
async function syncAll(ids) {
const tasks = ids.map((id) =>
limit(() => fetch(`https://api.example.com/items/${id}`).then((r) => r.json())),
);
const results = await Promise.all(tasks);
return results;
}
const started = [];
const tracker = pLimit(2);
const jobs = [1, 2, 3, 4].map((n) =>
tracker(async () => {
started.push(n);
console.log('running', n, 'active:', started.length);
await new Promise((r) => setTimeout(r, 100));
started.pop();
}),
);
await Promise.all(jobs);What the code does
P-Limit Concurrency Control for Task Queues reduces to the function syncAll.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
What to watch for
- External dependency:
p-limit— install it before running the snippet. - Uses
fetch, so it needs a browser context — it will not run as-is in Node without shims.
Using it
Signature: async function syncAll(ids)
The demo output is labeled (running), so every printed line maps back to its originating operation.
Key statements
await new Promise((r) => setTimeout(r, 100));
const results = await Promise.all(tasks);
await Promise.all(jobs);
Interactive Tools for This Topic
Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Are there third-party dependencies?
- `p-limit` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.