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.
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.
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));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.