1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
export async function asyncPool<T, V>(
array: T[],
poolLimit: number,
fn: (item: T) => Promise<V>,
): Promise<V[]> {
const results: Promise<V>[] = [];
const executing = new Set<Promise<V>>();
for (const item of array) {
const prom = Promise.resolve().then(() => fn(item));
results.push(prom);
if (poolLimit <= array.length) {
executing.add(prom);
prom.then(() => executing.delete(prom));
if (executing.size >= poolLimit) {
await Promise.race(executing);
}
}
}
return Promise.all(results);
}