-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Queue.ts
42 lines (34 loc) · 827 Bytes
/
Queue.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
interface Task<T> {
(): Promise<T>;
}
interface QueueItem {
reject: (reason?: unknown) => void;
resolve: (value: any) => void;
task: Task<unknown>;
}
export default class Queue {
private readonly queue: QueueItem[] = [];
private workerCount = 0;
constructor(private maxParallel: number) {}
run<T>(task: Task<T>): Promise<T> {
return new Promise((resolve, reject) => {
this.queue.push({ reject, resolve, task });
this.work();
});
}
private async work(): Promise<void> {
if (this.workerCount >= this.maxParallel) return;
this.workerCount++;
let entry: QueueItem | undefined;
while ((entry = this.queue.shift())) {
const { reject, resolve, task } = entry;
try {
const result = await task();
resolve(result);
} catch (err) {
reject(err);
}
}
this.workerCount--;
}
}