Skip to content
jshacks.dev
Async

Write an async queue with a fixed number of workers

Write an async queue with a fixed number of workers in JavaScript: a shared index, N loops and Promise.all. Plain Node.js 24, no libraries.

1 min read
Summarize in AI

You have a list of async tasks and want at most a fixed number running at once. Start that many worker loops, and let each one pull the next task until none are left.

JavaScript
const delay = (ms, v) => new Promise((r) => setTimeout(r, ms, v));

async function runQueue(tasks, workers) {
  const results = [];
  let next = 0;
  async function worker(id) {
    while (next < tasks.length) {
      const i = next++;
      results[i] = await tasks[i]();
      console.log(`worker ${id} finished task ${i}`);
    }
  }
  await Promise.all(Array.from({ length: workers }, (_, id) => worker(id)));
  return results;
}

const tasks = [40, 10, 10, 10].map((ms, i) => () => delay(ms, `t${i}`));
console.log(await runQueue(tasks, 2));
Text
worker 1 finished task 1
worker 1 finished task 2
worker 1 finished task 3
worker 0 finished task 0
[ 't0', 't1', 't2', 't3' ]

JavaScript runs one piece of code at a time, so next++ cannot be interleaved between two workers. The slow first task keeps worker 0 busy while worker 1 takes the three short ones. Results land in results[i], so they come back in task order whatever order they finished.

Tasks must be functions, not promises, or they have already started. A failing task rejects Promise.all and the other workers carry on with the remaining tasks unless you stop them.

Taggednode 24
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read
Node.js

Write CSV rows with a stream

Write CSV rows to a file stream in Node.js 24, quote fields that hold commas or quotes per RFC 4180, and wait for drain so memory stays flat.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.