This commit is contained in:
Peter Hedenskog 2025-03-07 15:26:45 +01:00
parent 1c6a02f67b
commit 351ba66989
1 changed files with 9 additions and 28 deletions

View File

@ -1,34 +1,15 @@
export async function runWithConcurrencyLimit(tasks, limit) {
const running = new Set();
async function runNext() {
if (tasks.length === 0) {
return;
}
const task = tasks.shift();
const promise = task()
.catch(error => {
async function worker() {
while (tasks.length > 0) {
const task = tasks.shift();
try {
await task();
} catch (error) {
throw error;
})
.finally(() => {
running.delete(promise);
void runNext();
});
running.add(promise);
if (running.size < limit) {
void runNext();
}
}
}
const starters = [];
for (let index = 0; index < limit && tasks.length > 0; index++) {
starters.push(runNext());
}
await Promise.allSettled(starters);
if (running.size > 0) {
await Promise.allSettled(Array.from(running));
}
const workers = Array.from({ length: limit }, () => worker());
await Promise.all(workers);
}