Worker
wx.CreateWorker
wx.createWorker(string scriptPath)
- Functional description:Create a Worker thread.
- Parameters: string scriptPath,The absolute path of the Worker entry file.
- Return value: Worker Worker object.
- Notes:
- Before using the interface, you need to configure the workers field in game.json, which indicates the Worker code root directory;
- scriptPath is the absolute path of the entry file and does not start with /;
- Currently, you can only create one Worker at most. Please call before creating the next WorkerWorker.terminate。
- Multithreaded Worker Guide (Mini Game)
js
// Create a normal worker
const worker = wx.createWorker("workers/index.js"); // Specify the worker's entry file absolute path
worker.onMessage(function (res) {
console.log(res);
});
worker.postMessage({
msg: "hello worker",
});
worker.terminate();Worker
Worker instance, the main thread can bewx.createWorkerInterface acquisition, which can be obtained through the global variable Worker in the Worker thread.
Properties
- Object env, Environment variables in the Worker.
| Properties | Type | Description |
|---|---|---|
| USER_DATA_PATH | string | User directory path in the file system (local path) |
Worker.onMessage
Worker.onMessage(function listener)
- Functional description:Listen to the event of the message sent by the main thread/Worker thread to the current thread.
- Parameters: function listener, Listener function for events of messages sent from the main thread/Worker thread to the current thread.
- Parameters: Object res
| Properties | Type | Description |
|---|---|---|
| message | Object | Messages sent from the main thread/Worker thread to the current thread |
Worker.postMessage
Worker.postMessage(function listener)
Functional description:Messages sent to the main thread/Worker thread.
Parameters: Object message, Messages to be sent.
Sample code:
- In worker thread
jsworker.postMessage({ msg: "hello from worker", });- In main thread
jsconst worker = wx.createWorker("workers/request/index.js"); worker.postMessage({ msg: "hello from main", });
Worker.terminate
Worker.terminate()
- Functional description:End the current Worker thread. Called only on the main thread worker object.