-
-
Notifications
You must be signed in to change notification settings - Fork 237
/
pool.ts
53 lines (43 loc) · 1.37 KB
/
pool.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import type { AbortSignal } from 'node-abort-controller';
import { AbortError } from './abort-error';
type Task<T> = (signal?: AbortSignal) => Promise<T>;
interface Pool {
submit<T>(task: Task<T>, signal?: AbortSignal): Promise<T>;
size: number;
readonly pending: number;
readonly drained: Promise<void>;
}
function createPool(size: number): Pool {
let pendingPromises: Promise<unknown>[] = [];
const pool = {
async submit<T>(task: Task<T>, signal?: AbortSignal): Promise<T> {
while (pendingPromises.length >= pool.size) {
AbortError.throwIfAborted(signal);
await Promise.race(pendingPromises).catch(() => undefined);
}
AbortError.throwIfAborted(signal);
const taskPromise = task(signal).finally(() => {
pendingPromises = pendingPromises.filter(
(pendingPromise) => pendingPromise !== taskPromise
);
});
pendingPromises.push(taskPromise);
return taskPromise;
},
size,
get pending() {
return pendingPromises.length;
},
get drained() {
// eslint-disable-next-line no-async-promise-executor
return new Promise<void>(async (resolve) => {
while (pendingPromises.length > 0) {
await Promise.race(pendingPromises).catch(() => undefined);
}
resolve(undefined);
});
},
};
return pool;
}
export { Pool, createPool };