-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloopAsync.ts
36 lines (32 loc) · 996 Bytes
/
loopAsync.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import assert from 'assert';
import {AnyFn} from '../types.js';
import {LoopAsyncSettlementType, kLoopAsyncSettlementType} from './types.js';
/** See {@link loop} */
export async function loopAsync<
TOtherParams extends unknown[],
TFn extends AnyFn<[number, ...TOtherParams]>,
>(
fn: TFn,
max: number,
settlement: LoopAsyncSettlementType,
...otherParams: TOtherParams
) {
assert(max >= 0);
if (settlement === kLoopAsyncSettlementType.oneByOne) {
for (let i = 0; i < max; i++) {
await fn(i, ...otherParams);
}
} else {
const promises: Array<Promise<unknown>> = Array(max);
for (let i = 0; i < max; i++) {
promises.push(fn(i, ...otherParams));
}
if (settlement === kLoopAsyncSettlementType.all) {
await Promise.all(promises);
} else if (settlement === kLoopAsyncSettlementType.allSettled) {
await Promise.allSettled(promises);
} else {
throw new Error(`Unknown promise settlement type ${settlement}`);
}
}
}