On this page
Worker
wx.CreateWorker
wx.createWorker(string scriptPath)
Functional description: Create a Worker thread
Parameters: string scriptPath,Absolute path of worker entry file
Return value: worker Worker object
Things To Note :
- Before using the interface, you need to configure the workers field in app.json, indicating 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 Worker Worker.terminate
Sample code:
js
// Create a regular worker
const worker = wx.createWorker('workers/index.js') // The filename specifies the path to the worker's entry file.
worker.onMessage(function (res) {
console.log(res)
})
worker.postMessage({
msg: 'hello worker'
})
worker.terminate()Worker
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(Object message)
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.