Skip to the page

Cancellation and concurrency control · senior

Async task queues, schedulers and chainable APIs

Many senior JavaScript tasks are the same idea in different clothes: keep a queue of pending work, run it one at a time (or N at a time) with promises, and expose a nice API — a cancellable scheduler, a sequential job queue, or a chainable object like driver.pick().drive(2).drop() that runs its steps in order.

The notes

What you must know

  • Sequential queue: keep a tail promise; each new job does tail = tail.then(job), with a catch so one failure doesn't break the queue.
  • Chainable async API: each method pushes a step into a queue and returns this. Start draining later (a microtask or setTimeout) so the whole synchronous chain is registered first.
  • Scheduler with cancel: a Map of id -> timer; cancel clears the timer and deletes the entry; ids come from a counter so they never collide.
  • Priority: insert by priority (sorted array or heap) and keep insertion order within the same priority.
  • Isolate errors per job (catch each one, report it through a callback or event) and continue.
  • Pause and resume: a flag checked before starting the next job.
  • Test with fake timers.

The red pen

Common traps: mistake → fix

  • Mistake: Starting work inside the first chained call

    Fix: later steps aren't registered yet.

  • Mistake: One rejected job breaks the tail promise forever

    Fix: catch before storing the tail.

  • Mistake: Leaking timers after cancel

    Fix: always clearTimeout and delete.

Easy to hard

Questions interviewers ask, easy to hard

  1. Implement a sequential async queue.
  2. Uber 2025: new UberDriver().pick('A').drive(2).drop('A').rest(10) with real delays.
  3. schedule(task, delay) returns an id; cancel(id) stops it (Uber task scheduler).
  4. Add priorities, then a concurrency limit of N.
  5. How would you test all of this?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview