-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
39 lines (35 loc) · 1002 Bytes
/
index.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
var csp = require('js-csp'),
assign = require('object-assign'),
debug = require('debug')('js-csp-worker'),
uuid = require('uuid').v4;
function worker(worker, opts) {
opts = opts || {};
var id = opts.id || uuid();
var close = !!opts.close || true;
var chi = opts.chi || csp.chan();
var cho = opts.cho || csp.chan();
worker.onmessage = function (msg) {
csp.putAsync(cho, assign({ worker_id: id }, msg));
}
csp.go(function* () {
while(true) {
var msg = yield csp.take(chi);
if (msg === csp.CLOSED) {
debug('Input channel %s closed', id);
worker.terminate()
if (close) {
cho.close();
debug('Output channel %s closed', id);
}
return
}
worker.postMessage(msg);
}
})
return {
id: id,
chi: chi,
cho: cho
};
}
module.exports = worker;