mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 18:42:34 +01:00
25 lines
742 B
TypeScript
25 lines
742 B
TypeScript
/** `Promise.allSettled` over `items`, with at most `limit` tasks in flight. */
|
|
export async function settleWithLimit<T, R>(
|
|
items: readonly T[],
|
|
limit: number,
|
|
task: (item: T) => Promise<R>,
|
|
): Promise<PromiseSettledResult<R>[]> {
|
|
const results = new Array<PromiseSettledResult<R>>(items.length);
|
|
let next = 0;
|
|
|
|
async function worker() {
|
|
while (next < items.length) {
|
|
const i = next++;
|
|
try {
|
|
results[i] = { status: "fulfilled", value: await task(items[i] as T) };
|
|
} catch (reason) {
|
|
results[i] = { status: "rejected", reason };
|
|
}
|
|
}
|
|
}
|
|
|
|
const workers = Math.max(1, Math.min(limit, items.length));
|
|
await Promise.all(Array.from({ length: workers }, worker));
|
|
return results;
|
|
}
|