0

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?

notabot
  • 40
  • 6
  • You definitely can't synchronously return the worker's message, since it doesn't exist yet. Do you want to return a promise that eventually resolves to the message? – Nicholas Tower Jan 27 '23 at 04:42
  • @NicholasTower Yes, that would work – notabot Jan 27 '23 at 04:43
  • The [documentation](//developer.mozilla.org/en/docs/Web/API/Web_Workers_API) has several examples. Which of these have you tried? If you want to use Promises, see [How do I convert an existing callback API to promises?](/q/22519784/4642212). – Sebastian Simon Jan 27 '23 at 04:44

1 Answers1

0

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);
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
RAllen
  • 1,235
  • 1
  • 7
  • 10
  • how would you embed it into a function ? – notabot Jan 27 '23 at 04:53
  • @notabot What do you mean by that? Why does the event listener need to be embedded into a function? – Sebastian Simon Jan 27 '23 at 04:54
  • @SebastianSimon so It would be easy to spawn workers and acquire results without blocking the main thread; also how would you implement a promise as the sources provided does not necessary provide an example – notabot Jan 27 '23 at 05:03
  • @notabot Just wrap this code in a Promise executor, pass it to a Promise constructor and return it from some function (e.g. `const spawnWorker = (mes) => new Promise((resolve) => {`…`})`). Call `resolve` in the `message` event listener. This is all mentioned in the documentation and the linked Q&A. Don’t use `onmessage`, though — this approach is very outdated. Use `worker.addEventListener("message", (e) => {`…`})` instead. – Sebastian Simon Jan 27 '23 at 05:10