1 | module.exports = class Queue {
|
2 | |
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | constructor(worker, options) {
|
9 | this._worker = worker;
|
10 | options = options || {};
|
11 | this._concurrency = options.concurrency || 1;
|
12 | this.tasks = [];
|
13 | this.total = 0;
|
14 | this.active = 0;
|
15 | }
|
16 |
|
17 |
|
18 | |
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | push(item, callback) {
|
25 | this.tasks.push({ item, callback });
|
26 | this.total++;
|
27 | this._next();
|
28 | }
|
29 |
|
30 |
|
31 | |
32 |
|
33 |
|
34 | _next() {
|
35 | if (this.active >= this._concurrency || !this.tasks.length) { return; }
|
36 | const { item, callback } = this.tasks.shift();
|
37 | let callbackCalled = false;
|
38 | this.active++;
|
39 | this._worker(item, (err) => {
|
40 | if (callbackCalled) { return; }
|
41 | this.active--;
|
42 | callbackCalled = true;
|
43 | if (callback) { callback(err); }
|
44 | this._next();
|
45 | });
|
46 | }
|
47 |
|
48 |
|
49 | |
50 |
|
51 |
|
52 | die() {
|
53 | this.tasks = [];
|
54 | }
|
55 | };
|