/
pool.js
65 lines (57 loc) · 1.36 KB
/
pool.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
'use strict';
const EventEmitter = require('events').EventEmitter;
const Task = require('./task.js').Task;
class Pool extends EventEmitter {
constructor(options) {
super();
options = options || {};
this.timeout = options.timeout || 10000;
this.style = options.style || 'callback';
this.limit = options.limit || 10;
this.running = 0;
this.queue = [];
}
next() {
this.running--;
if (!this.start() && !this.running) {
this.emit('idle');
}
}
start() {
if (this.running >= this.limit) return true;
const task = this.queue.shift();
if (!task) return false;
this.running++;
process.nextTick(task.run.bind(task));
return true;
}
add(task) {
task.pool = this;
this.queue.push(task);
this.start();
}
wrap(fn, options) {
options = options || {};
const timeout = options.timeout || this.timeout;
const style = options.style || this.style;
return function wrapped() {
const task = new Task({
fn,
timeout,
style,
args: [].slice.call(arguments),
});
this.add(task);
return task;
}.bind(this);
}
get promise() {
this.wrap = (fn, options) => {
delete this.wrap;
return this.wrap(fn, Object.assign({ style: 'promise' }, options));
};
return this;
}
}
exports.Task = Task;
exports.Pool = Pool;