⚡Flashcard Drill➔
NeetCode #956LC-2636MediumJavaScript
← Back to All Problems

#956 · #2636 · Promise Pool(任务调度器)

📌 Problem Statement & Constraints

Given an array of asynchronous functions functions and a concurrency limit n, return a Promise that resolves once all of them have completed, running at most n at a time.

💡 Core Algorithmic Approaches

  1. Use the worker-pool pattern: start min(n, functions.length) workers.
  2. Each worker loops, claiming the next task index with a shared cursor i++, awaiting it, and continuing.
  3. Wait for all workers with Promise.all(workers).
  4. The shared i++ is safe without locks because the event loop is single-threaded and the increment is not interleaved with an await.

💻 Benchmark Python3 Implementation

var promisePool = async function(functions, n) {
    let i = 0;                                // shared task cursor
    const worker = async () => {
        while (i < functions.length) {
            const idx = i++;                  // atomic in the single-threaded loop
            await functions[idx]();
        }
    };
    const workers = [];
    const cnt = Math.min(n, functions.length);
    for (let k = 0; k < cnt; k++) {
        workers.push(worker());
    }
    await Promise.all(workers);
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(m): m tasks are run; the wall-clock rate is governed by n.
💾 Space Complexity
O(n): n workers.

⚠️ Interview Pitfalls & Follow-ups

  • Doing Promise.all(functions.map(f => f())): that launches every task at once and violates the concurrency cap.
  • Awaiting tasks one by one in a plain loop: the pool degrades to serial execution.
  • Starting more workers than tasks: harmless but wasteful; Math.min(n, functions.length) avoids empty workers.
  • Omitting await Promise.all(workers): the function would resolve before the tasks finish.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related JavaScript Problems