Search code examples
javascriptwebpackvue.jsweb-worker

Web Worker loaded inline with worker-loader not working


I have the following code:

src/store/modules/outcome-analyzer/outcome-analyzer.js

import Worker from 'worker-loader!./set-hit-percentages.worker.js';

// ...

let actions = {
  setHitPercentages: function (context) {
    let worker = new Worker();
    // let players = resultsMutations.constructPlayersForSetHitPercentages(context.state);

    // worker.postMessage({
    //   message: 'get hit percentages',
    //   players: players,
    // });

    worker.postMessage({
      message: 'test',
      value: 'foobar',
    });

    worker.onmessage = function (e) {
      if (e.data.message === 'finished') {
        context.commit('outcomeAnalyzer/setHitPercentages', e.data.hitPercentages);
      }
    };
    worker.terminate();
  },
};

src/store/modules/outcome-analyzer/set-hit-percentages.worker.js

self.addEventListener('message', function (e) {
  debugger;
  if (e.data.message === 'test') {
    console.log(e.data.value);
  }
  else if (e.data.message === 'get hit percentages') {}
});

When setHitPercentages is called, it is supposed to post a message to the worker, and the worker is supposed to receive it. The worker never receives it. The debugger in set-hit-percentages.worker.js never is hit, and neither is the console.log.

  • Inside the setHitPercentages debugger, I see that Worker is defined. I also see that worker is defined after let worker = new Worker(); runs. worker has onmessasge and onerror methods, and it inherits other stuff like postMessage.
  • I have worker-loader in my node_modules. In package.json I have "worker-loader": "^1.1.1".
  • I'm using a worker in another part of my code, and it works. The code that works seems to be exactly analogous to the code I posted here that doesn't work, including the import Worker from 'worker-loader!./xxx-yyy-zzz.worker.js'; part.
  • I'm using Chrome. I also tried Safari, and it didn't work there either.
  • When I reproduce the problem, I don't start the other worker, but this answer says that multiple workers shouldn't cause problems. (I've also tried starting the other worker, terminating it, and then running the code in question, and the problem still occurs in that scenario as well. And when I comment out the code for the other worker, I also continue to have the problem.)
  • It's a Vue app started with vue-webpack-boilerplate.

Solution

  • You misplaced your worker.terminate();, which you probably wanted in your onmessage handler. As it is now, the worker is being spawned, but killed almost immediately after.