Skip to content

Commit be8024f

Browse files
committed
Adds batch promise utils
1 parent f4d8237 commit be8024f

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/system/promise.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,28 @@ export async function* asSettled<T>(promises: Promise<T>[]): AsyncIterable<Promi
6363
}
6464
}
6565

66+
export async function batch<T>(items: T[], batchSize: number, task: (item: T) => Promise<void>): Promise<void> {
67+
for (let i = 0; i < items.length; i += batchSize) {
68+
const batch = items.slice(i, i + batchSize);
69+
await Promise.allSettled(batch.map(item => task(item)));
70+
}
71+
}
72+
73+
export async function batchResults<T, R>(
74+
items: T[],
75+
batchSize: number,
76+
task: (item: T) => Promise<R>,
77+
): Promise<PromiseSettledResult<Awaited<R>>[]> {
78+
const results: PromiseSettledResult<Awaited<R>>[] = [];
79+
80+
for (let i = 0; i < items.length; i += batchSize) {
81+
const batch = items.slice(i, i + batchSize);
82+
results.push(...(await Promise.allSettled(batch.map(item => task(item)))));
83+
}
84+
85+
return results;
86+
}
87+
6688
export class PromiseCancelledError<T extends Promise<any> = Promise<any>> extends Error {
6789
constructor(
6890
public readonly promise: T,

0 commit comments

Comments
 (0)