"use strict"; import Config from './ClientConfig.mjs'; class WorkerWrapper { constructor() { this.worker = new Worker("worker.js"); // We could pass { type: "module" } as the 2nd argument here to allow Rollup code splitting to function as normal, but it's not supported by browsers yet } /** * Sets up the Web Worker that does the TensorFlow prediction. * Using a web worker avoids hanging the main thread. * @return {Promise} A Promise that resolves when setup is complete. */ setup(map_bounds, index) { // Arrow functions inherit the parent scope, including the "this" // special variable. return new Promise((resolve, reject) => { // Attach the listener first this.worker.addEventListener("message", (event) => { if(event.data.event !== "setup-complete") { reject(`Error: AIWorker responded with event ${event.data.event}, but 'setup-complete' was expected.`, event.data); return; } resolve(); }, { once: true }); // Ask the web worker to set itself up this.worker.postMessage({ event: "setup", setup_info: { bounds: map_bounds, index, Config } }); }) } /** * Uses the Web Worker to predict a row of signal strength values. * @param {number} latitude The latitude for which predictions should be made. * @return {Promise} A Promise returning the array of predictions calculated by the web worker. */ predict_row(latitude) { return new Promise((resolve, reject) => { // Attach the event listener.... this.worker.addEventListener("message", (event) => { if(event.data.event !== "result") { reject(`Error: AIWorker responded with event ${event.data.event}, but 'result' was expected.`, event.data); return; } resolve(event.data); }, { once: true }); // ....and send the request this.worker.postMessage({ event: "predict-row", latitude }); }); } end() { this.worker.postMessage({ event: "end" }) } } export default WorkerWrapper;