# Multi-threaded Worker

Some async tasks can be run in a worker. At the end of run, the results are returned to the main thread of the Mini Program. The worker runs in a separate global context and thread, and cannot directly call the methods of the main thread.

Data transfer between the worker and the main thread is accomplished using Worker.postMessage() to send data and Worker.onMessage() to receive data. The data to be transferred is not directly shared but copied.

# Procedures

Preview with Developer Tool

# 1. Configure Worker Information

In app.json, you can configure the directory where Worker code is placed. The code in the directory is packaged into a file:

Configuration example:

{
  "workers": "workers"
}

# 2. Add Worker Code Files

Based on the configuration in Step 1, create the following two entry files:

workers/request/index.js
workers/request/utils.js
workers/response/index.js

After the files are added, the directory structure is shown as below:

├── app.js
├── app.json
├── project.config.json
└── workers
    ├── request
    │   ├── index.js
    │   └── utils.js
    └── response
        └── index.js

# 3. Write Worker Code

Write the worker response code in workers/request/index.js.

const utils = require('./utils')

// In the worker thread execution context, a worker object is globally exposed and can be directly called by worker.onMessage/postMessage.
worker.onMessage(function (res) {
  console.log(res)
})

# 4. Initialize Worker in Main Thread

Initialize worker in app.js of the main thread.

const worker = wx.createWorker('workers/request/index.js') // The filename specifies the worker entry file path as an absolute path.

# 5. Main Thread Sends a Message to Worker

worker.postMessage({
  msg: 'hello worker'
})

For other APIs for worker object, refer to Worker APIs Description.

# Notes

  1. The maximum concurrency of worker is one. Use Worker.terminate() to terminate the current worker before creating the next one.
  2. The code in the worker can only require files in the specified worker path. It cannot reference other paths.
  3. The worker entry files are specified when calling wx.createWorker(). Developers can dynamically specify the worker entry files.
  4. wx APIs are not supported in workers.
  5. Workers cannot send messages to each other.