Skip to main content
Version: Next

Worker

Methods

onMessage

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

Reference

(callback: OnMessageCallback) => void
PropertyTypeDescription
callbackOnMessageCallbackThe callback function for the event that the main thread/worker thread sends a message to the current thread.

API Support

APIWeChat Mini-ProgramH5React Native
Worker.onMessage✔️

postMessage

Sends messages to the main thread/worker thread.

Reference

(message: Record<string, any>) => void
PropertyTypeDescription
messageRecord<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

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

In the main thread

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

API Support

APIWeChat Mini-ProgramH5React Native
Worker.postMessage✔️

terminate

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

Reference

() => void

API Support

APIWeChat Mini-ProgramH5React Native
Worker.terminate✔️

Parameters

OnMessageCallback

(result: OnMessageCallbackResult) => void
PropertyType
resultOnMessageCallbackResult

OnMessageCallbackResult

PropertyTypeDescription
messageRecord<string, any>The message sent by the main thread/worker thread to the current thread

API Support

APIWeChat Mini-ProgramH5React Native
Worker.onMessage✔️
Worker.postMessage✔️
Worker.terminate✔️