Show me how the concurrency limiter actually queues tasks.
Show me how the concurrency limiter actually queues tasks.
About sindresorhus/p-limit · 2 messages · last activity 5/25/2026
Perfect! Now I have the implementation details. Let me explain how the concurrency limiter queues tasks.
Task Queueing Implementation
The p-limit library uses a Queue data structure to manage pending tasks. Here's how it works [index.js:L3-L116]:
Core Queueing Logic
-
Queue Creation: A
Queueobject stores pending functions [index.js:L14]const queue = new Queue(); let activeCount = 0; -
Enqueue Function: When you call
limit(fn, ...args), the task is added to the queue via theenqueuefunction [index.js:L47-L56]:const enqueue = (function_, resolve, reject, arguments_) => { const queueItem = {reject}; new Promise(internalResolve => { queueItem.run = internalResolve; queue.enqueue(queueItem); }).then(run.bind(undefined, function_, resolve, arguments_)); if (activeCount < concurrency) { resumeNext(); } }; -
Resume Next: The
resumeNextfunction checks if capacity is available and dequeues the next task [index.js:L18-L23]:const resumeNext = () => { if (activeCount < concurrency && queue.size > 0) { activeCount++; queue.dequeue().run(); } }; -
Task Execution: The
runfunction executes a dequeued task and callsnext()when complete [index.js:L25-L41]:const run = async (function_, resolve, arguments_) => { const result = (async () => function_(...arguments_))(); resolve(result); try { await result; } catch {} next(); // Decrement activeCount and process next };
Flow Summary
- Tasks are enqueued immediately but only executed when activeCount < concurrency
- Each completed task triggers
next(), which decrementsactiveCountand processes the next queued item - The
pendingCountproperty reflectsqueue.size[index.js:L65-L67]
FOLLOW_UPS:
- How does the Queue data structure work internally?
- Can I adjust concurrency while tasks are queued?
- What happens when clearQueue() is called?
Want to ask your own question?
Open chat for sindresorhus/p-limit →Public Q&A. Generated by RepoPilot from the actual source of sindresorhus/p-limit. AI answers can be incomplete or stale — verify before relying on them.