Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/foundation/src/concurrency.ts
T

18 lines
538 B
TypeScript

export async function mapWithConcurrency<T>(items: readonly T[], concurrency: number, worker: (item: T, index: number) => Promise<void>): Promise<void> {
const limit = Math.max(1, Math.floor(concurrency));
let nextIndex = 0;
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
while (true) {
const index = nextIndex;
nextIndex += 1;
if (index >= items.length) {
return;
}
await worker(items[index] as T, index);
}
});
await Promise.all(runners);
}