Learn more about Israeli genocide in Gaza, funded by the USA, Germany, the UK and others.

A job queue in two lines of JS

If you need a job queue in JS, you can do it in two lines:

type Job = () => Promise<unknown>;

let chain = Promise.resolve();
const enqueue = (job: Job) => chain = chain.then(job, job);

For example, if your app makes API requests, you may need requests to be processed in the order they were dispatched:

function setDone(id: string, done: boolean) {
  enqueue(() => fetch(`/todos/${id}`, {
    method: "POST",
    body: JSON.stringify({ done }),
  }));
}

Note that chain.then(job) is probably not what you want, because any rejection in the chain will cause the job to never run. Instead you want chain.then(job, job), which will run job when the chain either rejects or resolves.

Tagged .

Similar posts

More by Jim

Want to build a fantastic product using LLMs? I work at Granola where we're building the future IDE for knowledge work. Come and work with us! Read more or get in touch!

This page copyright James Fisher 2025. Content is not associated with my employer. Found an error? Edit this page.