-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathdsQueue.js
44 lines (39 loc) · 1015 Bytes
/
dsQueue.js
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
class DsQueue {
constructor(concurrency = 1) {
this.concurrency = concurrency;
this.queue = [];
this.activeCount = 0;
}
async runTask(task) {
this.activeCount++;
try {
await task();
} catch (err) {
console.log('Task failed:', err);
} finally {
this.activeCount--;
this.next();
}
}
next() {
if (this.queue.length > 0 && this.activeCount < this.concurrency) {
const nextTask = this.queue.shift();
this.runTask(nextTask);
}
}
add(task) {
this.queue.push(task);
this.next();
}
onIdle() {
return new Promise((resolve) => {
const interval = setInterval(() => {
if (this.queue.length === 0 && this.activeCount === 0) {
clearInterval(interval);
resolve();
}
}, 10);
});
}
}
export default DsQueue;