forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise-worker.js
62 lines (56 loc) · 1.89 KB
/
promise-worker.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Worker from './worker-factory';
export function provideHostSide(workerFilename, methods) {
return function HostClass(...constructorArguments) {
const worker = new Worker(workerFilename);
const callbacks = new Map(); // msgID -> { resolve, reject }
let nextMessageID = 0;
worker.onmessage = ({ data }) => {
const { msgID, type } = data;
const { resolve, reject } = callbacks.get(msgID);
callbacks.delete(msgID);
if (type === 'success') {
resolve(data.result);
} else if (type === 'error') {
reject(data.error);
}
};
function makeMethod(method) {
return function(...paramArray) {
const msgID = nextMessageID++;
worker.postMessage({ msgID, type: 'method', method, paramArray });
return new Promise((resolve, reject) => {
callbacks.set(msgID, { resolve, reject });
});
};
}
for (const method of methods) {
this[method] = makeMethod(method);
}
worker.postMessage({ type: 'constructor', constructorArguments });
};
}
export function provideWorkerSide(workerGlobal, theClass) {
let theObject = null;
workerGlobal.onmessage = ({ data }) => {
if (data.type === 'constructor') {
theObject = new theClass(...data.constructorArguments);
} else if (data.type === 'method') {
const { msgID, method, paramArray } = data;
theObject[method](...paramArray).then(
result => {
workerGlobal.postMessage({ msgID, type: 'success', result });
},
error => {
workerGlobal.postMessage({
msgID,
type: 'error',
error: error.toString(),
});
}
);
}
};
}