-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjob.js
53 lines (43 loc) · 1.48 KB
/
job.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
function Job(args) {
// Declaring values for readability
this.options;
this.func;
this.resolve;
this.reject;
// Default values
this.args = [].slice.call(args);
this.context = Object.create(null);
this.delay = 0;
// Let's check if the user gives any options
if(typeof this.args[0] !== 'function') { this.options = this.args.shift(); }
// The first ele in the array MUST be a function here
this.func = this.args.shift();
if(typeof this.func !== 'function') {
throw new Error('You must provide a function to the constructor as one of the first two arguments.');
}
// Let's parse the options if the user gave us any
if(typeof this.options === 'number') {
this.delay = this.options;
} else if(typeof this.options === 'object') {
this.delay = this.options.delay || this.delay;
this.context = this.options.context || this.context;
}
}
Job.prototype.init = function initJob(resolve, reject) {
this.resolve = resolve;
this.reject = reject;
};
Job.prototype.runJob = function runJob(callback) {
function runningJob() {
var result = this.func.apply(this.context, this.args);
if(result && typeof result.then === 'function') {
// This job is a promise
result.then(this.resolve, this.reject);
} else {
this.resolve(result);
}
callback();
};
setTimeout(runningJob.bind(this), this.delay);
}
module.exports = Job;