Search code examples
javascriptfunctionworker

how do I return a value from a worker for a function in Javascript


I have a function that spawns a worker

function fetchFile(mes) {

    const worker = new Worker('worker.js');
    worker.postMessage(mes);

    //somehow return the message returned by the worker
}

worker.js:

self.onmessage = function (msg) {
    //some complex calculations
}

and I want to return the value calculated by the worker for the function

is there a way to do this?


Solution

  • In the worker:

    self.addEventListener("message", (msg) => {
      // Some complex calculations.
      postMessage(workerResult);
    });
    

    In the main app:

    const worker = new Worker("worker.js");
    
    worker.addEventListener("message", (e) => {
      result.textContent = e.data;
      console.log("Message received from worker");
    });
    worker.postMessage(mes);