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