-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathrpc-wrapper.js
More file actions
37 lines (37 loc) · 822 Bytes
/
rpc-wrapper.js
File metadata and controls
37 lines (37 loc) · 822 Bytes
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
export default function addMethods(worker, methods) {
let c = 0;
let callbacks = {};
worker.addEventListener('message', (e) => {
let d = e.data, evt;
if (d.type!=='RPC') return;
if (d.id) {
let f = callbacks[d.id];
if (f) {
delete callbacks[d.id];
if (d.error) {
f[1](Object.assign(Error(d.error.message), d.error));
}
else {
f[0](d.result);
}
}
}
else {
try {
evt = new Event(d.method);
} catch (e) {
evt = document.createEvent('Event');
evt.initEvent(d.method, false, false);
}
evt.data = d.params;
worker.dispatchEvent(evt);
}
});
methods.forEach( method => {
worker[method] = (...params) => new Promise( (a, b) => {
let id = ++c;
callbacks[id] = [a, b];
worker.postMessage({ type: 'RPC', id, method, params });
});
});
}