# Worker Basic Ability
Developers can directly use the basic capabilities of workers without using the encapsulation provided by the framework.
For data transmission between Worker and the main thread, both parties use Worker.postMessage() to send data, Worker.onMessage() To receive data, the transmitted data is not directly shared, but copied.
# Step
# 1. Configure Worker Information
Specify assets/workers as the only directory of workers code in the mini game framework, which is used for resource market or cross-project sharing business logic.
After selecting the assets/workers folder in the Project, the developer can "set as the workers folder" in the Inspector. Subsequent mini games will use the code in this folder as the workers code. At the same time, the developer will be asked if they want to use the workerSystem template, and choose not to use workerSystem here. Developers can directly use the basic capabilities of workers.
In concise mode, developers need to configure the directory where the Worker
code is placed in game.json
, and the code in the directory will be packaged into a file:
Configuration example:
{
"workers": "workers"
}
# 2. Add Worker Code File
According to the configuration in step 1, create the following two entry files in the workers directory:
workers/request/index.js
workers/request/utils.js
workers/response/index.js
In concise mode, there is no need to be in the assets/workers directory, you can customize it. After adding, the directory structure is as follows:
├── game.js
├── game.json
├── project.config.json
└── workers
├── request
│ ├── index.js
│ └── utils.js
└── response
└── index.js
# 3. Write Worker Code
Write Worker response code in workers/request/index.js
var utils = require('./utils')
// A `worker` object will be exposed globally in the execution context of the Worker thread, just call worker.onMessage/postMessage directly
worker.onMessage(function (res) {
console.log(res)
})
# 4. Initialize Worker in the main thread
Initialize Worker in the main thread's code
var worker = wx.createWorker('assets/workers/request/index.js') // The file name specifies the entry file path of the worker, absolute path
# 5. The main thread sends a message to the Worker
worker.postMessage({
msg:'hello worker'
})
For other interfaces of the worker object, please see worker interface description
# Tips
- 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 Worker can only require files in 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
wx
series of APIs are not supported in Worker - Sending messages between Workers is not supported
- Only JS files are supported in the Worker directory, and other types of static files need to be placed outside the Worker directory