S
S
SvinkaBacilka2020-05-21 21:49:41
JavaScript
SvinkaBacilka, 2020-05-21 21:49:41

How to work with workers in js?

I work with web workers and faced the following problem:

  • Data does not enter the worker throughworker.postMessage(someData)
  • Despite many examples on the Internet, I cannot call in the workerconsole.log('text')
  • How to debug it??? Not only does the console not work like this after changing the webpack worker file, it does not pull it up and works with the old


I would be very grateful for a detailed description of this technology and how to work with it.
PS I'm tired of reading articles with the same example from the documentation and about how stylish it is, possible, youthful and the main thread does not block.

vue.config.js config
configureWebpack: process.env.NODE_ENV === 'development'
    ? {
      module: {
        rules: [
          {
            test: /\.worker\.js$/,
            use: {
              loader: 'worker-loader',
              options: {
                inline: true
              }
            }
          }
        ]
      }
    }
    : {},

Worker code
self.addEventListener('message', event => {
  const data = event.data;
  switch (data.cmd) {
    case 'getInfo':
      // eslint-disable-next-line no-case-declarations
      const info = fetchInfo(data.token);
      self.postMessage(info);
      break;
    default:
      throw 'Unknown command'
  }
});

Worker creation code
import Worker from './custom.worker.js'

const worker = new Worker();
      worker.postMessage({
        cmd: 'getInfo',
        data: {
          token
        },
      })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor, 2020-05-21
@SvinkaBacilka

UDP:
To work with workers, install "worker-loader".
When you import a worker, you need to specify "worker-loader!" as a path prefix. Here is an example, see:

import Worker from 'worker-loader!./custom-worker.js'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question