RepoPilot

Show me how the concurrency limiter actually queues tasks.

About sindresorhus/p-limit · 2 messages · last activity 5/25/2026

Question

Show me how the concurrency limiter actually queues tasks.

RepoPilot

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

  1. Queue Creation: A Queue object stores pending functions [index.js:L14]

    const queue = new Queue();
    let activeCount = 0;
    
  2. Enqueue Function: When you call limit(fn, ...args), the task is added to the queue via the enqueue function [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();
        }
    };
    
  3. Resume Next: The resumeNext function 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();
        }
    };
    
  4. Task Execution: The run function executes a dequeued task and calls next() 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 decrements activeCount and processes the next queued item
  • The pendingCount property reflects queue.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.