JavaScript

Queue (Async Task Queue)

by @admin
12h ago
Apr 28, 2026
Public
A serialised async task queue that executes queued async functions one at a time, in order. Useful for sequencing operations that must not run concurrently (file writes, ordered API mutations, step-by-step wizards). add() returns a Promise that resolves/rejects when that specific task completes.
JavaScript
function createQueue() {
  let tail = Promise.resolve();
  return {
    add(task) {
      const result = tail.then(() => task());
      tail = result.catch(() => {}); // keep queue running on error
      return result;
    },
  };
}

// Usage
const q = createQueue();

q.add(() => fetch('/api/step1').then((r) => r.json())).then(console.log);
q.add(() => fetch('/api/step2').then((r) => r.json())).then(console.log);
// step2 only starts after step1 finishes
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.