runBoundedWorkerPool
JavaScript
// Runs zero-argument async task functions with a fixed concurrency limit.
export async function runBoundedWorkerPool(tasks, { concurrency = 4 } = {}) {
if (!Number.isInteger(concurrency) || concurrency < 1) {
throw new RangeError('concurrency must be a positive integer');
}
const queue = Array.from(tasks);
const results = new Array(queue.length);
let cursor = 0;
async function worker() {
while (cursor < queue.length) {
const index = cursor++;
try {
results[index] = { status: 'fulfilled', value: await queue[index]() };
} catch (error) {
results[index] = { status: 'rejected', reason: error };
}
}
}
const workers = Array.from({ length: Math.min(concurrency, queue.length) }, worker);
await Promise.all(workers);
return results;
}