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
| export default class WorkerWrapper { constructor(work, options) { this.worker = new work(); this.callbacks = new Map(); this.worker.onmessage = (event) => { const { id, data } = event.data; const callback = this.callbacks.get(id); if (callback) { callback(data); this.callbacks.delete(id); } }; }
postMessage(data, callback) { const id = Math.random().toString(36).substr(2); if (callback) { this.callbacks.set(id, callback); } this.worker.postMessage({ id, data }); }
// 终止进程 terminate() { this.worker.terminate(); } }
|