Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Run promises one at a time with a queue in JavaScript

113 a queue that runs promises one at a time, in order

hard

Write a queue whose add(task) returns a promise for that task's result but guarantees the tasks themselves run one after another, in the order added. Show that nothing starts synchronously, that a rejected task does not break the chain, and how differently the same three tasks behave under Promise.all.

Stuck? Three hints, smallest first
  1. 1. Keep a single promise as the tail of the chain. add is tail.then(task), and the new tail is what that produced.
  2. 2. If a task rejects, the tail must not stay rejected or every later task is skipped. Give the tail its own catch, separate from the promise you hand back.
  3. 3. The caller still needs the real result, including the rejection, so return the un-caught promise and keep the swallowed one for the chain.

The answer

const makeClock = () => {
  let now = 0;
  let seq = 0;
  const timers = [];
  const drainMicrotasks = async () => {
    for (let i = 0; i < 50; i++) await Promise.resolve();
  };
  return {
    now: () => now,
    wait: (ms) => new Promise((resolve) => timers.push({ at: now + ms, seq: seq++, resolve })),
    async runAll() {
      await drainMicrotasks();                  // microtasks first, then the clock
      while (timers.length) {
        timers.sort((a, b) => a.at - b.at || a.seq - b.seq);
        const next = timers.shift();
        now = next.at;
        next.resolve();
        await drainMicrotasks();
      }
      return now;
    },
  };
};

class SerialQueue {
  #tail = Promise.resolve();
  #depth = 0;

  add(task) {
    this.#depth++;
    const run = this.#tail.then(task);          // wait for whatever is ahead of you
    this.#tail = run.catch(() => {});           // a failure must not poison the chain
    return run.finally(() => { this.#depth--; });
  }

  get depth() { return this.#depth; }
}

const clock = makeClock();
const started = [];
const finished = [];
const job = (name, ms) => async () => {
  started.push(name);
  await clock.wait(ms);
  finished.push(name);
  return `${name} done`;
};

const queue = new SerialQueue();
const slow = queue.add(job('upload-receipt', 30));
const quick = queue.add(job('send-sms', 5));
const third = queue.add(job('update-ledger', 10));
const startedSynchronously = [...started];
const depthWhileQueued = queue.depth;

const serialAt = await clock.runAll();
const queued = await Promise.all([slow, quick, third]);
const depthAtTheEnd = queue.depth;

const parallelClock = makeClock();
const pStarted = [];
const pFinished = [];
const pJob = (name, ms) => async () => {
  pStarted.push(name);
  await parallelClock.wait(ms);
  pFinished.push(name);
  return name;
};
const together = Promise.all([pJob('upload-receipt', 30)(), pJob('send-sms', 5)(), pJob('update-ledger', 10)()]);
const parallelAt = await parallelClock.runAll();
const parallelResults = await together;

const failClock = makeClock();
const trail = [];
const failQueue = new SerialQueue();
const one = failQueue.add(async () => { trail.push('one'); await failClock.wait(5); return 'one'; });
const boom = failQueue.add(async () => { trail.push('two'); await failClock.wait(5); throw new Error('network down'); });
const three = failQueue.add(async () => { trail.push('three'); await failClock.wait(5); return 'three'; });
const rescued = boom.then(() => 'resolved after all', (e) => e.message);
await failClock.runAll();
const outcomes = [await one, await rescued, await three];

console.log('started :', started, '| synchronously:', startedSynchronously);
console.log('finished:', finished, '| clock:', serialAt);
console.log('parallel:', pFinished, '| clock:', parallelAt);
console.log('after a failure:', trail, outcomes);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('add starts nothing synchronously: the first task waits for a microtask', [startedSynchronously, depthWhileQueued], [[], 3]);
test('they started in the order they were added, one at a time', started, ['upload-receipt', 'send-sms', 'update-ledger']);
test('and finished in that order too, though the first was six times the slowest', finished, ['upload-receipt', 'send-sms', 'update-ledger']);
test('so the clock advanced by the sum of the durations, which is what serial costs', serialAt, 45);
test('every caller still got its own result back', [queued, depthAtTheEnd], [['upload-receipt done', 'send-sms done', 'update-ledger done'], 0]);
test('Promise.all starts all three at once, so they finish by duration', pFinished, ['send-sms', 'update-ledger', 'upload-receipt']);
test('its clock cost is the longest task, not the sum, and results keep input order', [parallelAt, parallelResults], [30, ['upload-receipt', 'send-sms', 'update-ledger']]);
test('a rejected task does not break the queue: the one behind it still ran', trail, ['one', 'two', 'three']);
test('and the rejection reached its own caller, not the queue', outcomes, ['one', 'network down', 'three']);

The queue is one promise long. tail.then(task) says "run this after whatever is currently last", and the result becomes the new last. That is the entire mechanism, and it gives you ordering for free without a list, a lock or a scheduler.

The two-promise split in add is the part that is easy to get wrong. The chain's tail must be a promise that cannot reject, or one failing task leaves the tail rejected and every later then skips its callback — the queue silently stops working. But the caller does need the rejection, so add returns the un-caught promise and keeps a caught copy for itself. Two references to the same work, with two different error policies.

Set against Promise.all, the trade is explicit: the queue costs the sum of the durations and Promise.all costs the longest. Serialising is not a performance choice, it is a correctness one — writes that must not interleave, a device that accepts one command at a time, an API that rate-limits per connection. Note also that started is empty immediately after three add calls: then schedules a microtask, so even the first task begins after the current synchronous block finishes. If that matters, the first task can be started eagerly, but then add stops being uniform.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.