# Worker

The worker instance can be obtained via the wx.createWorker API in the main thread and via the global variable worker in the worker thread.

# Methods

# Worker.postMessage(Object message)

Sends messages to the main thread/worker thread.

# Worker.terminate()

Ends the current worker thread. This API can only be called on the worker object in the main thread.

# Worker.onMessage(function callback)

Listens on the event that the main thread/worker thread sends a message to the current thread.

# Sample Code

The basic configuration is required to run the following code. For more information on the basics and configuration methods, see Multithreading.

const worker = wx.createWorker('workers/request/index.js') // The filename specifies the worker entry file path as an absolute path.

worker.onMessage(function (res) {
  console.log(res)
})

worker.postMessage({
  msg: 'hello worker'
})

worker.terminate()
点击咨询小助手