forked from leetcode-tools/leetcode-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
51 lines (41 loc) · 1.13 KB
/
queue.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
'use strict';
var _ = require('underscore');
var config = require('./config');
function Queue(tasks, ctx, onTask) {
this.tasks = _.clone(tasks) || [];
this.ctx = ctx || {};
this.onTask = onTask;
this.error = null;
}
Queue.prototype.addTask = function(task) {
this.tasks.push(task);
return this;
};
Queue.prototype.addTasks = function(tasks) {
this.tasks = this.tasks.concat(tasks);
return this;
};
Queue.prototype.run = function(concurrency, onDone) {
this.concurrency = concurrency || config.network.concurrency || 1;
this.onDone = onDone;
const self = this;
for (let i = 0; i < this.concurrency; ++i) {
setImmediate(function() { self.workerRun(); });
}
};
Queue.prototype.workerRun = function() {
// no more tasks, quit now
if (this.tasks.length === 0) {
if (--this.concurrency === 0 && this.onDone)
this.onDone(this.error, this.ctx);
return;
}
const task = this.tasks.shift();
const self = this;
this.onTask(task, self, function(e) {
if (e) self.error = e;
// TODO: could retry failed task here.
setImmediate(function() { self.workerRun(); });
});
};
module.exports = Queue;