-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtaskQueue.js
42 lines (36 loc) · 831 Bytes
/
taskQueue.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
import { EventEmitter } from "events"
export class TaskQueue extends EventEmitter {
constructor(concurrency = 1) {
super()
this.queue = []
this.concurrency = concurrency
this.running = 0
}
async processTask() {
while (this.running < this.concurrency && this.queue.length > 0) {
this.running++
const task = this.queue.shift()
try {
await task()
} catch (error) {
this.emit("error", error)
} finally {
this.running--
this.processTask() // PROCESS NEXT TASK IF AVAILABLE
}
}
}
enqueue(task) {
this.queue.push(task)
this.processTask()
}
size() {
return this.queue.length + this.running
}
getQueue() {
return [...this.queue]
}
isRunning() {
return this.running > 0 || this.queue.length > 0
}
}