Skip to the solution
MediumFrontend4 min read

Implement a Promise Queue (TaskQueue) with concurrency

932 views

The problem

Problem, as an interviewer would state it: "Build a TaskQueue class with an add(task) method and a configurable concurrency limit. Unlike a bare function wrapper, I want to be able to inspect how many tasks are currently running and how many are waiting."

Examples:

Code
const q = new TaskQueue(2);
q.add(() => doWork(1));
q.add(() => doWork(2));
q.add(() => doWork(3)); // waits, since 2 are already running
console.log(q.running, q.pending); // 2, 1

Clarifying questions expected:

  • Is this genuinely different in real capability from a plain p-limit-style function, or mainly a different API shape?
  • Should running/pending be live-readable properties, or only available via a method call?
  • Does add() need to return a promise the caller can await for that specific task's own result?

Code / implementation expected: Yes — real, direct, live proof that immediately after enqueueing tasks beyond the concurrency limit, the object's own running/pending state correctly reports the real, current numbers.

  • promise
  • queue
  • concurrency

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a TaskQueue's own running/pending state correctly reports 2 and 1 immediately after enqueueing 3 tasks at concurrency 2

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 95 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Binary search implementation

Continue