Search code examples
javascriptpromiseweb-worker

How to make a javascript variable defined in javascript worker?


I have this variable in a javascript file editorArea.js.

var editor = CodeMirror.fromTextArea(document.getElementById('editor'), {});

when I call this variable from another javascript worker file worker.js inside of a promise.

myPromise.then(() => {
editor.doFunction()
}

the variable example is undefined.

How to make it defined?


Solution

  • Web workers have some big limitations - necessary ones since the DOM was never designed with thread safety in mind. You cannot access global variables in the main code, or anything in the DOM from a web worker, and you will find that trying anything in a web worker like editor.doFunction() will not work. The scopes are hermetically sealed off from one another. Instead, you need to send messages to the worker via postMessage, and receive replies via onMessage per javascript web workers - how do I pass arguments? (as suggested by mpm).

    The data you pass cannot be DOM elements or anything in the DOM at all or you would violate thread safety. Instead you need to extract any data you need to do heavy duty work on into a separate object and pass it to the worker to process.

    As examples, in an application I work on, I pass data for image processing and OCR to web workers for concurrent processing in order not to freeze the UI thread. But I have to copy the data out of the DOM first.