-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (74 loc) · 1.93 KB
/
index.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'use strict';
const EventEmitter = require('events')
, measured = require('measured');
class PromisQueue extends EventEmitter {
constructor(options) {
super();
this._state = new QueueState(options || {});
const st = this._state, _this = this;
st.next = function () {
st.processed.mark();
st.processing--;
if (!st.resuming) {
st.resuming = true;
process.nextTick(() => {
st.resuming = false;
_this.emit('next');
_this._start();
});
}
};
}
get length() {
return this._state.pending.length;
}
get currentConcurrency() {
const st = this._state;
return st.pending.length > st.highWatermark ? st.softLimit : st.limit;
}
add(p) {
checkGenerator(p);
this._state.pending.push(p);
this._start();
return this.length;
}
prepend(p) {
checkGenerator(p);
this._state.pending.unshift(p);
this._start();
return this.length;
}
stats() {
return this._state.processed.toJSON();
}
_start() {
const st = this._state, maxproc = this.currentConcurrency;
if (st.pending.length) {
for (let p; st.pending.length > 0 && st.processing < maxproc; st.processing++) {
try {
p = st.pending.shift()();
} catch (e) {
p = Promise.reject(e);
}
p.then(st.next).catch(st.next);
this.emit('start', p);
}
if (!st.pending.length) this.emit('drained');
}
}
}
module.exports = PromisQueue;
class QueueState {
constructor(options) {
this.limit = options.limit || 10;
this.softLimit = options.softLimit || this.limit * 2;
this.highWatermark = options.highWatermark || this.softLimit * 5;
this.pending = [];
this.processing = 0;
this.processed = new measured.Meter();
}
}
function checkGenerator(fn) {
if (typeof fn !== 'function' || fn.length > 0)
throw new TypeError('Promise factory function expected.');
}