UNPKG

1.27 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3class Queue {
4 /**
5 * A really simple queue with concurrency.
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 * Push a task to the queue.
16 */
17 push(item, callback) {
18 this.tasks.push({ item, callback });
19 this.total++;
20 this._next();
21 }
22 /**
23 * Process next job in queue.
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 * Stops processing queued jobs.
46 */
47 die() {
48 this.tasks = [];
49 }
50}
51exports.default = Queue;
52//# sourceMappingURL=queue.js.map
\No newline at end of file