# Multi-thread Worker (Beta)
Supported by Base Library 3.0.45 and above. For tool debugging, please use version 1.8.46 or higher, and for the SDK, please use version 2.41.0 or above.
Some asynchronous processing tasks can be placed in a Worker to run, and after execution is complete, the results can be returned to the Mini-Program main thread. The Worker runs in a separate global context and thread and cannot directly call methods from the main thread.
# Usage Process
# 1. Configure Worker Information
In app.json, you can configure the directory where the Worker code is placed.
Configuration example:
{
"workers": "workers"
}
# 2. Add Worker Code Files
Based on the configuration in step 1, create an entry file workers/request/index.js in the code directory.
# 3. Write Worker Code
Write the Worker response code in workers/request/index.js.
// In the Worker thread execution context, a worker object is globally exposed. You can directly call worker.onMessage/postMessage.
worker.onMessage(function (res) {
console.log(res)
})
# 4. Initialize the Worker in the Main Thread
Initialize the Worker in the main thread's code app.js.
const worker = wx.createWorker('workers/request/index.js') // The filename specifies the path to the Worker's entry file, using an absolute path.
# 5. Send Messages from the Main Thread to the Worker
worker.postMessage({
msg: 'hello worker'
})
Notes
- The maximum concurrent number of Workers is limited to 1. Before creating a new one, terminate the current Worker using Worker.terminate().
- The code inside the Worker can only require files within the specified Worker path and cannot reference files from other paths.
- The entry file for the Worker is specified when calling
wx.createWorker(). Developers can dynamically specify the Worker entry file. - APIs starting with wx are not supported inside the Worker.
- Sending messages between Workers is not supported.
- Only JS files can be placed in the Worker directory. Other types of static files need to be placed outside the Worker directory.