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
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:
By configuring it in the above way, all the JS files under the workers directory will be packaged into one JS file and be part of the first package of the mini program.
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
Write Worker Code
Write the worker response code in workers/request/index.js
.
const utils = require('./utils')
worker.onMessage(function (res) {
console.log(res)
})
Initialize Worker in Main Thread
Initialize worker in app.js of the main thread.
const worker = wx.createWorker('workers/request/index.js')
Main Thread Sends a Message to Worker
worker.postMessage({
msg: 'hello worker'
})
Notes
The maximum concurrency of worker is one. Use Worker.terminate() to terminate the current worker before creating the next one; The code in the worker can only require files in the specified worker path. It cannot reference other paths;
The worker entry files are specified when calling wx.createWorker(). Developers can dynamically specify the worker entry files; wx APIs are not supported in workers;
Workers cannot send messages to each other.
Was this page helpful?