# Multithreaded Worker
Some asynchronous processing tasks, can be placed in the Worker to run, until the end of the run, and then return the results to the Weixin Mini Program main thread.Worker runs in a separate global context and thread and cannot directly call methods of the main thread.
Data transfer between the worker and the main thread, both parties use Worker.postMessage () to send the data, and [Workers.onMessage ()]]]((Worker.onMessage)) to receive the data. The transmitted data is not shared directly, but is copied.
# Use Procedure
# 1. Configuring Worker Information
Inapagejsonyou can configure the directory where theWorkercode resides. All the JS code in the directory will eventually be packaged into a single JS file:
Example configuration:
{
"workers": "workers"
}
With the above configuration, all JS files in the workers directory are packaged as a single JS file as part of the Weixin Mini Program first package.
Weixin Mini Program There is an upper limit to the size of the initial packet (currently 2M), so that worker code does not take up the initial block size, starting with the base library v2.27.3 supports packaging worker code as a subpackage.(Need to update the developer tools to the latest nightly version)
Example worker code configured as a subcontract:
{
"workers": {
"path": "workers",
"isSubpackage": true // true 表示把 worker 打包为分包。默认 false。填 false 时等同于 { "workers": "workers" }
}
}
# 2. Adding a Worker Code File
Following 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.js
Once added, the directory structure is as follows:
├── app.js
├── app.json
├── project.config.json
└── workers
├── request
│ ├── index.js
│ └── utils.js
└── response
└── index.js
# 3. Writing Worker Code
Write Worker response code inworkers / request / index.js
const utils = require('./utils')
// In the context of the Worker thread execution, a worker object is exposed globally, and you can call worker.onMessage / postMessage directly
worker.onMessage(function (res) {
console.log(res)
})
# 4. Initialize the Worker in the main thread
Initialize the Worker in the main thread's code apagejs
const worker = wx.createWorker('workers/request/index.js') // 文件名指定 worker 的入口文件路径,绝对路径
Starting with the base library v2.27.3, if the worker code is configured to be subcontracted, you need to download the worker code through the wx.preDownloadSubpackage interface, and then initialize the worker
var task = wx.preDownloadSubpackage({
packageType: "workers",
success(res) {
console.log("load worker success", res)
var worker = wx.createWorker("workers/request/index.js") // 创建 worker。 如果 worker 分包没下载完就调 createWorker 的话将报错
},
fail(res) {
console.log("load worker fail", res)
}
})
task.onProgressUpdate(res => {
console.log(res.progress) // 可通过 onProgressUpdate 接口监听下载进度
console.log(res.totalBytesWritten)
console.log(res.totalBytesExpectedToWrite)
})
# 5. The main thread sends a message to the Worker
worker.postMessage({
msg: 'hello worker'
})
For additional interfaces to the worker object, see worker interface explaination
# Note
- The maximum number of concurrent workers is limited to 1. Please use Worker.terminate () before creating the next one
- Code within a worker can only require files within the specified worker path, and cannot refer to other paths
- The worker entry file is specified by wx.createWorker () . The developer can dynamically specify the worker entry file
- The
wxseries API is not supported in Worker - Sending messages between workers is not supported
- The Worker directory only supports the placement of JS files, other types of static files need to be placed outside the Worker directory
- The base library v2.18.1 supports the use of workers within plug-ins.Accordingly, the
workerscode path is configured in``[plugin.json]] in, i.e., a path relative to the root directory of the plugin code package.