title: Worker

sidebar_label: Worker

Methods

onMessage

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

Reference

  1. (callback: OnMessageCallback) => void
Property Type Description
callback OnMessageCallback The callback function for the event that the main thread/worker thread sends a message to the current thread.

API Support

API WeChat Mini-Program H5 React Native
Worker.onMessage ✔️

postMessage

Sends messages to the main thread/worker thread.

Reference

  1. (message: Record<string, any>) => void
Property Type Description
message Record<string, any> The message to be sent, which must be a serializable object in the format of JavaScript key-value.

Sample Code

In the worker thread

  1. worker.postMessage({
  2. msg: 'hello from worker'
  3. })

In the main thread

  1. const worker = Taro.createWorker('workers/request/index.js')
  2. worker.postMessage({
  3. msg: 'hello from main'
  4. })

API Support

API WeChat Mini-Program H5 React Native
Worker.postMessage ✔️

terminate

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

Reference

  1. () => void

API Support

API WeChat Mini-Program H5 React Native
Worker.terminate ✔️

Parameters

OnMessageCallback

  1. (result: OnMessageCallbackResult) => void
Property Type
result OnMessageCallbackResult

OnMessageCallbackResult

Property Type Description
message Record<string, any> The message sent by the main thread/worker thread to the current thread

API Support

API WeChat Mini-Program H5 React Native
Worker.onMessage ✔️
Worker.postMessage ✔️
Worker.terminate ✔️