worker.js (1285B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */ 4 5 let msgId = 1; 6 /** 7 * @memberof utils/utils 8 * @static 9 */ 10 function workerTask(worker, method) { 11 return function (...args) { 12 return new Promise((resolve, reject) => { 13 const id = msgId++; 14 worker.postMessage({ id, method, args }); 15 16 const listener = ({ data: result }) => { 17 if (result.id !== id) { 18 return; 19 } 20 21 worker.removeEventListener("message", listener); 22 if (result.error) { 23 reject(result.error); 24 } else { 25 resolve(result.response); 26 } 27 }; 28 29 worker.addEventListener("message", listener); 30 }); 31 }; 32 } 33 34 function workerHandler(publicInterface) { 35 return function onTask(msg) { 36 const { id, method, args } = msg.data; 37 const response = publicInterface[method].apply(null, args); 38 39 if (response instanceof Promise) { 40 response 41 .then(val => self.postMessage({ id, response: val })) 42 .catch(error => self.postMessage({ id, error })); 43 } else { 44 self.postMessage({ id, response }); 45 } 46 }; 47 } 48 49 export { workerTask, workerHandler };