-
Notifications
You must be signed in to change notification settings - Fork 0
/
TaskQueue.js
38 lines (30 loc) · 872 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
import {EventEmitter} from "events"
export class TaskQueue extends EventEmitter {
constructor(concurrency) {
super()
this.concurrency = concurrency
this.running = 0
this.queue = []
}
pushTask(task) {
this.queue.push(task)
process.nextTick(this.next.bind(this))
return this
}
next() {
if(this.queue.length===0&&this.running===0){
this.emit("empty")
}
while (this.running < this.concurrency && this.queue.length) {
const task = this.queue.shift()
task((err) => {
if(err){
this.emit("error",err)
}
this.running--
process.nextTick(this.next.bind(this)) //EL FAKRA HANA
})
this.running++
}
}
}