-
Notifications
You must be signed in to change notification settings - Fork 1
/
queue.es6
60 lines (51 loc) · 1011 Bytes
/
queue.es6
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
54
55
56
57
58
59
60
class Queue {
constructor(act, win) {
this.act = act;
this.win = win || 1; // execute window
this.queue = [];
this.prom = null;
}
fire() {
while (this.win && this.queue.length) {
this.shoot(this.shift());
}
}
shoot(pack) {
this.win -= 1;
this.act(pack.data).then(ret => {
this.proceed(pack.resolve, ret);
}, err => {
this.proceed(pack.reject, err);
});
}
proceed(cb, ret) {
this.eject(cb, ret);
this.fire();
}
eject(cb, ret) {
return cb(ret), this.win += 1;
}
push(data, resolve, reject) {
return this.queue.push({data, resolve, reject});
}
shift() {
return this.queue.shift();
}
promise(data) {
return this.prom = new Promise((ok, err) => this.push(data, ok, err));
}
promiseArr(arr) {
return this.prom = Promise.all(arr.map(data => this.promise(data)));
}
enQueue(data) {
this.promise(data);
this.fire();
return this.prom;
}
enQueueAll(arr) {
this.promiseArr(arr);
this.fire();
return this.prom;
}
}
module.exports = Queue;