AniUI Academy

An async queue that preserves order

mediumAsync & Promises+250 XPPractice

Autosave is the classic case: every keystroke can enqueue a save, the saves must not overlap or arrive out of order, and one failure must not wedge the queue for the rest of the session.

Implement a class AsyncQueue. push(task) takes a zero-argument function returning a promise, appends it to the queue, and returns a promise that settles with that task's own result. Tasks run strictly one at a time, in the order they were pushed, including tasks pushed while an earlier one is still running. If a task rejects, only the promise returned by its own push call rejects — the queue carries on with the next task.

Arguments

task() => Promise<T>
The work to enqueue, passed to queue.push. Zero-argument, returns a promise.

Returns

Promise<T> — push returns a promise that settles with the task's own result. A rejecting task only rejects its own promise — the queue keeps processing.

Examples

const queue = new AsyncQueue();
const results = await Promise.all([
  queue.push(async () => "a"),
  queue.push(async () => "b"),
  queue.push(async () => "c"),
]);
// results === ["a", "b", "c"] — one at a time, in push order

Serial execution, in push order.

const queue = new AsyncQueue();
const first = queue
  .push(async () => { throw new Error("save failed"); })
  .catch((e) => "caught:" + e.message);
const second = queue.push(async () => "ok");
// await first  === "caught:save failed"
// await second === "ok" — queue carried on

A rejection only affects the task's own promise.

What it has to do

  • Never run two tasks at the same time.
  • Start tasks in the order they were pushed, including ones pushed mid-run.
  • Resolve each push with that task's own resolved value.
  • Reject only the failing task's promise and keep processing the rest.

Notes

  • Keep a tail promise and chain each new task onto it. The new tail swallows errors so one rejection can't poison the chain.
  • Tasks pushed while an earlier one is running still go to the back of the queue — chaining preserves order for free.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
4 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.