# Calling actions from a worker

Workers (opens new window) are used to optimize the main thread. In a worker, you can perform complex calculations that could lead to drawdowns in the main thread. And then you need to transfer the result of calculations to the main thread. If you use vuex, then most often you will need to transfer the results of calculating workers to the storage.

It's very easy to do this with Vuexok. Vuexok allows you to proxy action methods into workers.

# Improvement of worker initialization

After initializing the worker, you need to pass it to the vuexokWorkerWrapper method

import { vuexokWorkerWrapper } from 'vuexok/dist/vuexokWorkerWrapper'
const worker = new Worker('./worker')
vuexokWorkerWrapper(worker)

That being said, you can also use comlink (opens new window) with vuexok.

# Improvement of the worker

Now let's move on to the worker code. In order for the actions of the module to be available in the worker, 3 lines are enough. In the worker code, import the vuexokWorkerGetActions method, which will return methods for calling the module's actions.

import { vuexokWorkerGetActions } from 'vuexok/dist/vuexokWorkerGetActions'

The worker does not know anything about our store and modules, so we need to import the module type into the worker.

Since we do not want vuex and the code of our module in the worker, we only import the type of the module. Typescript versions higher than 3.8 (opens new window) only allow importing of the type.

import type {countModule} from '@/store/modules/countModule'

Now we can access the actions of our module from the worker. The vuexokWorkerGetActions method takes one required parameter - the path to the vuex module.

const countModuleActions = vuexokWorkerGetActions<typeof countModule>('countModule')

Simple example (20 seconds)

# Action error handling

For interaction between the worker and the main thread, the postMessage (opens new window) method is used.

postMessage uses the structured cloning algorithm (opens new window). Implementation in ff does not support passing native errors objects (opens new window).

For this original error object, vuexok passes the message field of the Error (opens new window) object to the worker, and a new instance ofnew Error (message)is created inside the worker.