forked from andywer/threads.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjob.js
78 lines (64 loc) · 1.64 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import EventEmitter from 'eventemitter3';
export default class Job extends EventEmitter {
constructor(pool) {
super();
this.pool = pool;
this.thread = null;
this.runArgs = [];
this.sendArgs = [];
pool.emit('newJob', this);
}
run(...args) {
if (args.length === 0) {
throw new Error('Cannot call .run() without arguments.');
}
this.runArgs = args;
return this;
}
send(...args) {
if (this.runArgs.length === 0) {
throw new Error('Cannot .send() before .run().');
}
this.sendArgs = args;
this.emit('readyToRun');
return this;
}
executeOn(thread) {
const onProgress = (...args) => this.emit('progress', ...args);
const onMessage = (...args) => {
this.emit('done', ...args);
thread.removeListener('progress', onProgress);
};
const onError = (...args) => {
this.emit('error', ...args);
thread.removeListener('progress', onProgress);
};
thread
.on('progress', onProgress)
.once('message', onMessage)
.once('error', onError)
.run(...this.runArgs)
.send(...this.sendArgs);
this.thread = thread;
this.emit('threadChanged');
return this;
}
promise() {
// Always return a promise
return new Promise((resolve) => {
// If the thread isn't set, listen for the threadChanged event
if (!this.thread) {
this.once('threadChanged', () => {
resolve(this.thread.promise());
});
} else {
resolve(this.thread.promise());
}
});
}
destroy () {
this.removeAllListeners();
delete this.runArgs;
delete this.sendArgs;
}
}