# Worker(Beta)
Supported since Base Library 3.0.45 and above. Use Developer Tools 1.8.46+ for debugging and SDK 2.41.0+.
# wx.createWorker
Worker wx.createWorker(string scriptPath)
Creates a Worker thread.
Parameters
string scriptPath
The absolute path of the worker entry file.
Return Value
Worker
Worker object.
Notes
- The
workersfield must be configured inapp.json(not supported in plugins yet) before using this API, indicating the root directory of theworkercode. scriptPathis the absolute path of the entry file and does not start with/.- Currently, only one
Workercan be created at most. Please callWorker.terminatebefore creating the nextWorker.
Sample Code
const worker = wx.createWorker('workers/request/index.js') // The filename specifies the absolute path of the worker entry file.
worker.onMessage(function (res) {
console.log(res)
})
worker.postMessage({
msg: 'hello worker'
})
worker.terminate()
# Worker
# Worker.onMessage
Worker.onMessage(function listener)
Listens for the event when the main thread/Worker thread sends a message to the current thread.
Parameters
function listener
The listener function for the event when the main thread/Worker thread sends a message to the current thread.
Parameters
Object res
| Property | Type | Description |
|---|---|---|
| message | Object | The message sent by the main thread/Worker thread to the current thread. |
# Worker.postMessage
Worker.postMessage(Object message)
Sends a message to the main thread/Worker thread.
Parameters
Object message
The message to be sent.
Sample Code
In the worker thread:
worker.postMessage({
msg: 'hello from worker'
})
In the main thread:
const worker = wx.createWorker('workers/request/index.js')
worker.postMessage({
msg: 'hello from main'
})
# Worker.terminate
Worker.terminate()
Terminates the current Worker thread. Can only be called on the worker object in the main thread.