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
.
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
.worker-loader
in my node_modules
. In package.json
I have "worker-loader": "^1.1.1"
.import Worker from 'worker-loader!./xxx-yyy-zzz.worker.js';
part.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.