Multi-Process Worker
Some asynchronous processing tasks can be placed in Worker for running. After the running is completed, the results are returned to the main thread of the mini program. Worker runs in a separate global context and thread, and cannot directly call the method of the main thread.
For data transmission between Worker and main thread, both parties use Worker.postMessage() to send data and Worker.onMessage() to receive data. The transmitted data is not directly shared, but copied.
Usage process
Configure Worker information
In app.json, you can configure the directory where the Worker code is placed. All JS codes in the directory will eventually be packaged into a JS file:
Configuration example:
{
"workers": "workers"
}Through the above configuration, all JS files in the workers directory will be packaged into a JS file and used as part of the first package of the mini program.
Add Worker code file
According to the configuration in step 1, create the following two entry files in the code directory:
workers/request/index.js
workers/request/utils.js
workers/response/index.jsAfter adding, the directory structure is as follows:
├── app.js
├── app.json
├── project.config.json
└── workers
├── request
│ ├── index.js
│ └── utils.js
└── response
└── index.jsWrite Worker code
Write 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)
})Initialize Worker in the main thread
Initialize Worker in the main thread code app.js
const worker = wx.createWorker('workers/request/index.js') // The filename specifies the worker entry file path as an absolute path.The main thread sends a message to the Worker
worker.postMessage({
msg: 'hello worker'
})Notes
- The maximum number of concurrent workers is limited to 1. Please use Worker.terminate() to end the current worker before creating the next one.
- The code in the worker can only require files in the specified worker path and cannot reference other paths;
- The entry file of the worker is specified by wx.createWorker() , and the developer can dynamically specify the entry file of the worker;
- The wx series API is not supported in the worker;
- Workers do not support sending messages between each other;
- Only JS files are supported in the Worker directory, and other types of static files need to be placed outside the Worker directory.