Files
OpenFrame/lib/async-pool.ts

30 lines
698 B
TypeScript

/**
* Execute async work with a bounded number of in-flight tasks.
*/
export async function runWithConcurrency<T>(
items: T[],
limit: number,
worker: (item: T) => Promise<void>
): Promise<void> {
if (items.length === 0) return;
const concurrency = Math.max(1, Math.floor(limit));
let nextIndex = 0;
async function runWorker(): Promise<void> {
while (true) {
const currentIndex = nextIndex;
nextIndex += 1;
if (currentIndex >= items.length) {
return;
}
await worker(items[currentIndex]);
}
}
const workerCount = Math.min(concurrency, items.length);
await Promise.all(Array.from({ length: workerCount }, () => runWorker()));
}