Readme

Summary

Async Pool: Promise.all for Bulk Operations. Taken from this article.

asyncPool is a utility with the same functionality as Promise.all + Array.map that keeps the number of concurrent executions at or below a set number.

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);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
November 18, 2023