# 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 workers field must be configured in app.json (not supported in plugins yet) before using this API, indicating the root directory of the worker code.
  • scriptPath is the absolute path of the entry file and does not start with /.
  • Currently, only one Worker can be created at most. Please call Worker.terminate before creating the next Worker.

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.

© FinClip with ❤ , Since 2017