MainThreadController.js
921 Bytes
let fakeId = 0;
class MainThreadController {
constructor(options) {
this.actionHandlerMap = {};
this.worker = new Worker(options.workerUrl, { name: options.workerName });
this.worker.onmessage = this.onmessage.bind(this);
}
onmessage = (e) => {
const { id, response } = e.data;
if (!this.actionHandlerMap[id]) return;
this.actionHandlerMap[id].call(this, response);
delete this.actionHandlerMap[id];
this.worker.terminate();
};
postMessage = (action) => {
const id = fakeId++;
return new Promise((resolve, reject) => {
const message = {
id,
...action
};
this.worker.postMessage(message);
this.actionHandlerMap[id] = (response) => {
resolve(response);
};
});
};
}
export default MainThreadController;