An async queue that preserves order
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 orderSerial 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 onA 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
pushwith that task's own resolved value. - Reject only the failing task's promise and keep processing the rest.
Notes
- Keep a
tailpromise 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.
- 1.runs tasks in push order
- 2.never runs two tasks at once
- 3.keeps going after a task rejects
- 4.a task pushed while one is running goes to the back
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.