tencent cloud

Tencent Cloud Super App as a Service

Worker

Download
Focus Mode
Font Size
Last updated: 2025-02-24 17:10:42

wx.CreateWorker

wx.createWorker(string scriptPath)

Feature description:Creates a worker thread.
Parameter:string scriptPath. The absolute path to the worker’s entry file.
Return value: Worker.A worker object.
Notes:
Before using the API, you need to go to the game.json file, and configure the workers field, which indicates the worker code root directory.
scriptPath should be the absolute path to the entry file and should not start with /.
Currently, only one worker can be created at a time. Before creating another worker, you must call Worker.terminate.
Example:
// 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, which can be obtained in the main thread via wx.createWorker , or in the worker thread via the global variable worker.

Property

Object env.The environment variables within the worker.
Property
Type
Description
USER_DATA_PATH
string
The path to the user directory in the file system (local path).

Worker.onMessage

Worker.onMessage(function listener)

Feature description:Listens for messages sent from the main thread/worker thread to the current thread.
Parameter: function listener. listener for the event where the main/Worker thread sends messages to the current thread.
ParameterObject res
Property
Type
Description
message
Object
Messages sent by the main/Worker thread to the current thread.

Worker.postMessage

Worker.postMessage(Object message)

Feature description:Messages sent to the main/worker thread.
Parameter: Object message. Messages to be sent.
Example:
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'
})

Woker.terminate

Worker.terminate()

Feature description:Ends the current worker thread. This can only be called on the worker object in the main thread.




Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback