提交 91b5bc3f 编写于 作者: G Gloria

Update docs against 10739

Signed-off-by: wusongqing<wusongqing@huawei.com>
上级 d02dd0eb
...@@ -17,9 +17,10 @@ import worker from '@ohos.worker'; ...@@ -17,9 +17,10 @@ import worker from '@ohos.worker';
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ---------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------ | | --------------------------------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| parentPort | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes | Yes | Object of the worker thread used to communicate with the host thread.| | workerPort<sup>9+</sup> | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Yes | Object of the worker thread used to communicate with the host thread. |
| parentPort<sup>(deprecated)</sup> | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes | Yes | Object of the worker thread used to communicate with the host thread.<br>This attribute is deprecated since API version 9. You are advised to use **workerPort<sup>9+</sup>** instead.|
## WorkerOptions ## WorkerOptions
...@@ -28,17 +29,641 @@ Provides options that can be set for the **Worker** instance to create. ...@@ -28,17 +29,641 @@ Provides options that can be set for the **Worker** instance to create.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
| Name | Type | Readable| Writable| Description | | Name| Type| Readable| Writable| Description |
| ------ | --------- | ---- | ---- | ---------------------- | | ---- | -------- | ---- | ---- | -------------- |
| name | string | Yes | Yes | Name of the worker thread. | | name | string | Yes | Yes | Name of the worker thread.|
## Worker ## ThreadWorker<sup>9+</sup>
Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [EventTarget](#eventtarget). Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [WorkerEventTarget](#workereventtarget9).
### constructor<sup>9+</sup>
constructor(scriptURL: string, options?: WorkerOptions)
A constructor used to create a **Worker** instance.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------- | ---- | ------------------------------------------------------------ |
| scriptURL | string | Yes | Directory of the script to be executed by the **Worker** instance.<br>In the FA or stage model, DevEco Studio creates a **Worker** project in either of the following scenarios:<br>(a) The script directory is at the same level as the **pages** directory.<br>(b) The script directory is at a different level from the **pages** directory.|
| options | [WorkerOptions](#workeroptions) | No | Options that can be set for the **Worker** instance. |
**Return value**
| Type | Description |
| ------ | --------------------------------------------------------- |
| Worker | Returns the **Worker** instance created; returns **undefined** if the **Worker** instance fails to be created.|
**Example**
```js
import worker from '@ohos.worker';
// Create a Worker instance.
// In the FA model, the worker script directory and pages directory are at the same level.
const workerFAModel01 = new worker.ThreadWorker("workers/worker.js", {name:"first worker in FA model"});
// In the FA model, the worker script directory and pages directory are at different levels.
const workerFAModel02 = new worker.ThreadWorker("../workers/worker.js");
// In the stage model, the worker script directory and pages directory are at the same level.
const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"});
// In the stage model, the worker script directory and pages directory are at different levels.
const workerStageModel02 = new worker.ThreadWorker('entry/ets/pages/workers/worker.ts');
// For the script URL "entry/ets/workers/worker.ts" in the stage model:
// entry is the value of the name attribute under module in the module.json5 file.
// ets indicates the programming language in use.
```
Depending on whether the worker script directory and **pages** directory are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file.
(1) The worker script directory and **pages** directory are at the same level.
In the FA model:
```json
"buildOption": {
"sourceOption": {
"workers": [
"./src/main/ets/MainAbility/workers/worker.ts"
]
}
}
```
In the stage model:
```json
"buildOption": {
"sourceOption": {
"workers": [
"./src/main/ets/workers/worker.ts"
]
}
}
```
(2) The worker script directory and **pages** directory are at different levels.
In the FA model:
```json
"buildOption": {
"sourceOption": {
"workers": [
"./src/main/ets/workers/worker.ts"
]
}
}
```
In the stage model:
```json
"buildOption": {
"sourceOption": {
"workers": [
"./src/main/ets/pages/workers/worker.ts"
]
}
}
```
### postMessage<sup>9+</sup>
postMessage(message: Object, options?: PostMessageOptions): void
Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information).
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| message | Object | Yes | Message to be sent to the worker thread. |
| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.|
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.postMessage("hello world");
var buffer = new ArrayBuffer(8);
workerInstance.postMessage(buffer, [buffer]);
```
### on<sup>9+</sup>
on(type: string, listener: WorkerEventListener): void
Adds an event listener for the worker thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ---------------------- |
| type | string | Yes | Type of the event to listen for. |
| listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs. Callback to invoke when an event of the specified type occurs.|
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.on("alert", (e)=>{
console.log("alert listener callback");
})
```
### once<sup>9+</sup>
once(type: string, listener: WorkerEventListener): void
Adds an event listener for the worker thread and removes the event listener after it is invoked once.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ---------------------- |
| type | string | Yes | Type of the event to listen for. |
| listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs. Callback to invoke when an event of the specified type occurs.|
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.once("alert", (e)=>{
console.log("alert listener callback");
})
```
### off<sup>9+</sup>
off(type: string, listener?: WorkerEventListener): void
Removes an event listener for the worker thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ---------------------------- |
| type | string | Yes | Type of the event for which the event listener is to be removed. |
| listener | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.|
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.off("alert");
```
### terminate<sup>9+</sup>
terminate(): void
Terminates the worker thread to stop it from receiving messages.
**System capability**: SystemCapability.Utils.Lang
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.terminate();
```
### onexit<sup>9+</sup>
onexit?: (code: number) =&gt; void
Defines the event handler to be called when the worker thread exits. The handler is executed in the host thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| code | number | No | Code indicating the worker thread exit state.|
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.onexit = function(e) {
console.log("onexit");
}
```
### onerror<sup>9+</sup>
onerror?: (err: ErrorEvent) =&gt; void
Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------- | ---- | ---------- |
| err | [ErrorEvent](#errorevent) | No | Error data.|
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.onerror = function(e) {
console.log("onerror");
}
```
### onmessage<sup>9+</sup>
onmessage?: (event: MessageEvent\<T>) =&gt; void
Defines the event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the host thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | ---------------------- |
| event | [MessageEvent](#messageevent) | No | Message received.|
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.onmessage = function(e) {
// e: MessageEvent<T>. The usage is as follows:
// let data = e.data;
console.log("onmessage");
}
```
### onmessageerror<sup>9+</sup>
onmessageerror?: (event: MessageEvent\<T>) =&gt; void
Defines the event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | ---------- |
| event | [MessageEvent](#messageevent) | No | Error data.|
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.onmessageerror= function(e) {
console.log("onmessageerror");
}
```
## WorkerEventTarget<sup>9+</sup>
### addEventListener<sup>9+</sup>
addEventListener(type: string, listener: WorkerEventListener): void
Adds an event listener for the worker thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ---------------- |
| type | string | Yes | Type of the event to listen for.|
| listener | [WorkerEventListener](#workereventlistener9) | Yes | Callback to invoke when an event of the specified type occurs. |
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.addEventListener("alert", (e)=>{
console.log("alert listener callback");
})
```
### removeEventListener<sup>9+</sup>
removeEventListener(type: string, callback?: WorkerEventListener): void
Removes an event listener for the worker thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ---------------------------- |
| type | string | Yes | Type of the event for which the event listener is to be removed. |
| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.|
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.removeEventListener("alert");
```
### dispatchEvent<sup>9+</sup>
dispatchEvent(event: Event): boolean
Dispatches the event defined for the worker thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | --------------- | ---- | ---------------- |
| event | [Event](#event) | Yes | Event to dispatch.|
**Return value**
| Type | Description |
| ------- | ------------------------------- |
| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.|
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.dispatchEvent({type:"alert"});
```
### removeAllListener<sup>9+</sup>
removeAllListener(): void
Removes all event listeners for the worker thread.
**System capability**: SystemCapability.Utils.Lang
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.removeAllListener();
```
## ThreadWorkerGlobalScope<sup>9+</sup>
Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **DedicatedWorkerGlobalScope** class inherits from [GlobalScope<sup>9+</sup>](#globalscope9).
### postMessage<sup>9+</sup>
postMessage(messageObject: Object, options?: PostMessageOptions): void
Sends a message to the host thread from the worker thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| message | Object | Yes | Message to be sent to the worker thread. |
| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.|
**Example**
```js
// main.js
import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.postMessage("hello world");
workerInstance.onmessage = function(e) {
// let data = e.data;
console.log("receive data from worker.js");
}
```
```js
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.workerPort;
parentPort.onmessage = function(e){
// let data = e.data;
parentPort.postMessage("receive data from main.js");
}
```
### close<sup>9+</sup>
close(): void
Terminates the worker thread to stop it from receiving messages.
**System capability**: SystemCapability.Utils.Lang
**Example**
```js
// main.js
import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("workers/worker.js");
```
```js
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.workerPort;
parentPort.onmessage = function(e) {
parentPort.close()
}
```
### onmessage<sup>9+</sup>
onmessage?: (event: MessageEvent\<T>) =&gt; void
Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | ------------------------ |
| event | [MessageEvent](#messageevent) | No | Message received.|
**Example**
```js
// main.js
import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.postMessage("hello world");
```
```js
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.workerPort;
parentPort.onmessage = function(e) {
console.log("receive main.js message");
}
```
### onmessageerror<sup>9+</sup>
onmessageerror?: (event: MessageEvent\<T>) =&gt; void
Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | ---------- |
| event | [MessageEvent](#messageevent) | No | Error data.|
**Example**
```js
// main.js
import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("workers/worker.js");
```
```js
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.workerPort;
parentPort.onmessageerror= function(e) {
console.log("worker.js onmessageerror")
}
```
## WorkerEventListener<sup>9+</sup>
(event: Event): void | Promise&lt;void&gt;
Implements event listening.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | --------------- | ---- | -------------- |
| event | [Event](#event) | Yes | Event class for the callback to invoke.|
**Return value**
| Type | Description |
| ------------------------------------- | ------------------------------- |
| void&nbsp;\|&nbsp;Promise&lt;void&gt; | Returns no value or returns a **Promise**.|
**Example**
```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.addEventListener("alert", (e)=>{
console.log("alert listener callback");
})
```
## GlobalScope<sup>9+</sup>
Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [WorkerEventTarget](#workereventtarget9).
### Attributes
**System capability**: SystemCapability.Utils.Lang
| Name| Type | Readable| Writable| Description |
| ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- |
| name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.|
| self | [GlobalScope](#globalscope9)&nbsp;&amp;&nbsp;typeof&nbsp;globalThis | Yes | No | **GlobalScope** itself. |
### onerror<sup>9+</sup>
onerror?: (ev: ErrorEvent) =&gt; void
Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------- | ---- | ---------- |
| ev | [ErrorEvent](#errorevent) | No | Error data.|
**Example**
```js
// main.js
import worker from '@ohos.worker';
const workerInstance = new worker.ThreadWorker("workers/worker.js")
```
```js
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.workerPort
parentPort.onerror = function(e){
console.log("worker.js onerror")
}
```
## Worker<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorker<sup>9+</sup>](#threadworker9) instead.
Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [EventTarget](#eventtarget).
### constructor ### constructor<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorker.constructor<sup>9+</sup>](#constructor9) instead.
constructor(scriptURL: string, options?: WorkerOptions) constructor(scriptURL: string, options?: WorkerOptions)
...@@ -50,7 +675,7 @@ A constructor used to create a **Worker** instance. ...@@ -50,7 +675,7 @@ A constructor used to create a **Worker** instance.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ------------------------------- | ---- | ------------------------------------------------------------ | | --------- | ------------------------------- | ---- | ------------------------------------------------------------ |
| scriptURL | string | Yes | Directory of the script to be executed by the **Worker** instance.<br>In the FA or stage model, DevEco Studio creates a **Worker** project in either of the following scenarios:<br>(a) The script directory is at the same level as the **pages** directory.<br>(b) The script directory is at a different level from the **pages** directory. | scriptURL | string | Yes | Directory of the script to be executed by the **Worker** instance.<br>In the FA or stage model, DevEco Studio creates a **Worker** project in either of the following scenarios:<br>(a) The script directory is at the same level as the **pages** directory.<br>(b) The script directory is at a different level from the **pages** directory.|
| options | [WorkerOptions](#workeroptions) | No | Options that can be set for the **Worker** instance. | | options | [WorkerOptions](#workeroptions) | No | Options that can be set for the **Worker** instance. |
**Return value** **Return value**
...@@ -126,7 +751,10 @@ In the stage model: ...@@ -126,7 +751,10 @@ In the stage model:
} }
} }
``` ```
### postMessage ### postMessage<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorker.postMessage<sup>9+</sup>](#postmessage9) instead.
postMessage(message: Object, options?: PostMessageOptions): void postMessage(message: Object, options?: PostMessageOptions): void
...@@ -153,7 +781,10 @@ workerInstance.postMessage(buffer, [buffer]); ...@@ -153,7 +781,10 @@ workerInstance.postMessage(buffer, [buffer]);
``` ```
### on ### on<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorker.on<sup>9+</sup>](#on9) instead.
on(type: string, listener: EventListener): void on(type: string, listener: EventListener): void
...@@ -166,7 +797,7 @@ Adds an event listener for the worker thread. ...@@ -166,7 +797,7 @@ Adds an event listener for the worker thread.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------- | ---- | ---------------- | | -------- | ------------------------------- | ---- | ---------------- |
| type | string | Yes | Type of the event to listen for.| | type | string | Yes | Type of the event to listen for.|
| listener | [EventListener](#eventlistener) | Yes | Callback to invoke when an event of the specified type occurs. | | listener | [EventListener](#eventlistener) | Yes | Callback to invoke when an event of the specified type occurs. |
**Example** **Example**
...@@ -178,7 +809,10 @@ workerInstance.on("alert", (e)=>{ ...@@ -178,7 +809,10 @@ workerInstance.on("alert", (e)=>{
``` ```
### once ### once<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorker.once<sup>9+</sup>](#once9) instead.
once(type: string, listener: EventListener): void once(type: string, listener: EventListener): void
...@@ -191,7 +825,7 @@ Adds an event listener for the worker thread and removes the event listener afte ...@@ -191,7 +825,7 @@ Adds an event listener for the worker thread and removes the event listener afte
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------- | ---- | ---------------- | | -------- | ------------------------------- | ---- | ---------------- |
| type | string | Yes | Type of the event to listen for.| | type | string | Yes | Type of the event to listen for.|
| listener | [EventListener](#eventlistener) | Yes | Callback to invoke when an event of the specified type occurs. | | listener | [EventListener](#eventlistener) | Yes | Callback to invoke when an event of the specified type occurs. |
**Example** **Example**
...@@ -203,7 +837,10 @@ workerInstance.once("alert", (e)=>{ ...@@ -203,7 +837,10 @@ workerInstance.once("alert", (e)=>{
``` ```
### off ### off<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorker.off<sup>9+</sup>](#off9) instead.
off(type: string, listener?: EventListener): void off(type: string, listener?: EventListener): void
...@@ -213,10 +850,10 @@ Removes an event listener for the worker thread. ...@@ -213,10 +850,10 @@ Removes an event listener for the worker thread.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------- | ---- | ---------------------- | | -------- | ------------------------------- | ---- | -------------------- |
| type | string | Yes | Type of the event for which the event listener is to be removed. | | type | string | Yes | Type of the event for which the event listener is to be removed.|
| listener | [EventListener](#eventlistener) | No | Callback of the event listener to remove. | | listener | [EventListener](#eventlistener) | No | Callback of the event listener to remove. |
**Example** **Example**
...@@ -226,7 +863,10 @@ workerInstance.off("alert"); ...@@ -226,7 +863,10 @@ workerInstance.off("alert");
``` ```
### terminate ### terminate<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorker.terminate<sup>9+</sup>](#terminate9) instead.
terminate(): void terminate(): void
...@@ -242,7 +882,10 @@ workerInstance.terminate(); ...@@ -242,7 +882,10 @@ workerInstance.terminate();
``` ```
### onexit ### onexit<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onexit<sup>9+</sup>](#onexit9) instead.
onexit?: (code: number) =&gt; void onexit?: (code: number) =&gt; void
...@@ -266,7 +909,10 @@ workerInstance.onexit = function(e) { ...@@ -266,7 +909,10 @@ workerInstance.onexit = function(e) {
``` ```
### onerror ### onerror<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onerror<sup>9+</sup>](#onerror9) instead.
onerror?: (err: ErrorEvent) =&gt; void onerror?: (err: ErrorEvent) =&gt; void
...@@ -290,7 +936,10 @@ workerInstance.onerror = function(e) { ...@@ -290,7 +936,10 @@ workerInstance.onerror = function(e) {
``` ```
### onmessage ### onmessage<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onmessage<sup>9+</sup>](#onmessage9) instead.
onmessage?: (event: MessageEvent\<T>) =&gt; void onmessage?: (event: MessageEvent\<T>) =&gt; void
...@@ -316,7 +965,10 @@ workerInstance.onmessage = function(e) { ...@@ -316,7 +965,10 @@ workerInstance.onmessage = function(e) {
``` ```
### onmessageerror ### onmessageerror<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onmessageerror<sup>9+</sup>](#onmessageerror9) instead.
onmessageerror?: (event: MessageEvent\<T>) =&gt; void onmessageerror?: (event: MessageEvent\<T>) =&gt; void
...@@ -340,10 +992,14 @@ workerInstance.onmessageerror= function(e) { ...@@ -340,10 +992,14 @@ workerInstance.onmessageerror= function(e) {
``` ```
## EventTarget ## EventTarget<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [WorkerEventTarget<sup>9+</sup>](#workereventtarget9) instead.
### addEventListener<sup>(deprecated)</sup>
### addEventListener > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [addEventListener<sup>9+</sup>](#addeventlistener9) instead.
addEventListener(type: string, listener: EventListener): void addEventListener(type: string, listener: EventListener): void
...@@ -368,7 +1024,10 @@ workerInstance.addEventListener("alert", (e)=>{ ...@@ -368,7 +1024,10 @@ workerInstance.addEventListener("alert", (e)=>{
``` ```
### removeEventListener ### removeEventListener<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [removeEventListener<sup>9+</sup>](#removeeventlistener9) instead.
removeEventListener(type: string, callback?: EventListener): void removeEventListener(type: string, callback?: EventListener): void
...@@ -378,10 +1037,10 @@ Removes an event listener for the worker thread. ...@@ -378,10 +1037,10 @@ Removes an event listener for the worker thread.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------- | ---- | ---------------------- | | -------- | ------------------------------- | ---- | ------------------------ |
| type | string | Yes | Type of the event for which the event listener is to be removed.| | type | string | Yes | Type of the event for which the event listener is to be removed.|
| callback | [EventListener](#eventlistener) | No | Callback of the event listener to remove. | | callback | [EventListener](#eventlistener) | No | Callback of the event listener to remove. |
**Example** **Example**
...@@ -391,7 +1050,10 @@ workerInstance.removeEventListener("alert"); ...@@ -391,7 +1050,10 @@ workerInstance.removeEventListener("alert");
``` ```
### dispatchEvent ### dispatchEvent<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [dispatchEvent<sup>9+</sup>](#dispatchevent9) instead.
dispatchEvent(event: Event): boolean dispatchEvent(event: Event): boolean
...@@ -419,7 +1081,10 @@ workerInstance.dispatchEvent({type:"alert"}); ...@@ -419,7 +1081,10 @@ workerInstance.dispatchEvent({type:"alert"});
``` ```
### removeAllListener ### removeAllListener<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [removeAllListener<sup>9+</sup>](#removealllistener9) instead.
removeAllListener(): void removeAllListener(): void
...@@ -435,12 +1100,18 @@ workerInstance.removeAllListener(); ...@@ -435,12 +1100,18 @@ workerInstance.removeAllListener();
``` ```
## DedicatedWorkerGlobalScope ## DedicatedWorkerGlobalScope<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>](#threadworkerglobalscope9) instead.
Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. This class inherits from [WorkerGlobalScope](#workerglobalscope). Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. This class inherits from [WorkerGlobalScope](#workerglobalscope).
### postMessage ### postMessage<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>](#threadworkerglobalscope9).postMessage<sup>9+</sup> instead.
postMessage(messageObject: Object, options?: PostMessageOptions): void postMessage(messageObject: Object, options?: PostMessageOptions): void
...@@ -452,7 +1123,7 @@ Sends a message to the host thread from the worker thread. ...@@ -452,7 +1123,7 @@ Sends a message to the host thread from the worker thread.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| message | Object | Yes | Message to be sent to the worker thread. | | message | Object | Yes | Message to be sent to the worker thread. |
| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| | options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.|
**Example** **Example**
...@@ -478,7 +1149,10 @@ parentPort.onmessage = function(e){ ...@@ -478,7 +1149,10 @@ parentPort.onmessage = function(e){
``` ```
### close ### close<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>](#threadworkerglobalscope9).close<sup>9+</sup> instead.
close(): void close(): void
...@@ -503,7 +1177,10 @@ parentPort.onmessage = function(e) { ...@@ -503,7 +1177,10 @@ parentPort.onmessage = function(e) {
``` ```
### onmessage ### onmessage<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>](#threadworkerglobalscope9).onmessage<sup>9+</sup> instead.
onmessage?: (event: MessageEvent\<T>) =&gt; void onmessage?: (event: MessageEvent\<T>) =&gt; void
...@@ -513,8 +1190,8 @@ Defines the event handler to be called when the worker thread receives a message ...@@ -513,8 +1190,8 @@ Defines the event handler to be called when the worker thread receives a message
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | ---------------------- | | ------ | ----------------------------- | ---- | ------------------------ |
| event | [MessageEvent](#messageevent) | No | Message received.| | event | [MessageEvent](#messageevent) | No | Message received.|
**Example** **Example**
...@@ -535,7 +1212,10 @@ parentPort.onmessage = function(e) { ...@@ -535,7 +1212,10 @@ parentPort.onmessage = function(e) {
``` ```
### onmessageerror ### onmessageerror<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>](#threadworkerglobalscope9).onmessageerror<sup>9+</sup> instead.
onmessageerror?: (event: MessageEvent\<T>) =&gt; void onmessageerror?: (event: MessageEvent\<T>) =&gt; void
...@@ -589,7 +1269,10 @@ Defines the event. ...@@ -589,7 +1269,10 @@ Defines the event.
| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created.| | timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created.|
## EventListener ## EventListener<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [WorkerEventListener<sup>9+</sup>](#workereventlistener9) instead.
(evt: Event): void | Promise&lt;void&gt; (evt: Event): void | Promise&lt;void&gt;
...@@ -645,7 +1328,10 @@ Holds the data transferred between worker threads. ...@@ -645,7 +1328,10 @@ Holds the data transferred between worker threads.
| data | T | Yes | No | Data transferred between threads.| | data | T | Yes | No | Data transferred between threads.|
## WorkerGlobalScope ## WorkerGlobalScope<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [GlobalScope<sup>9+</sup>](#globalscope9) instead.
Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtarget). Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtarget).
...@@ -653,13 +1339,16 @@ Implements the running environment of the worker thread. The **WorkerGlobalScope ...@@ -653,13 +1339,16 @@ Implements the running environment of the worker thread. The **WorkerGlobalScope
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
| Name| Type | Readable| Writable| Description | | Name| Type | Readable| Writable| Description |
| ---- | ------------------------------------------------------------ | ---- | ---- | --------------------------------------- | | ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- |
| name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.| | name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.|
| self | [WorkerGlobalScope](#workerglobalscope)&nbsp;&amp;&nbsp;typeof&nbsp;globalThis | Yes | No | **WorkerGlobalScope**. | | self | [WorkerGlobalScope](#workerglobalscope)&nbsp;&amp;&nbsp;typeof&nbsp;globalThis | Yes | No | **WorkerGlobalScope**. |
### onerror ### onerror<sup>(deprecated)</sup>
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [GlobalScope<sup>9+</sup>](#globalscope9).onerror instead.
onerror?: (ev: ErrorEvent) =&gt; void onerror?: (ev: ErrorEvent) =&gt; void
...@@ -689,27 +1378,31 @@ parentPort.onerror = function(e){ ...@@ -689,27 +1378,31 @@ parentPort.onerror = function(e){
} }
``` ```
## More Information ## More Information
### Sequenceable Data Types ### Sequenceable Data Types
| Type | Remarks | Supported | | Type | Remarks | Supported|
| ------------------- | -------------------------------------------------------- | -------------------- | | ------------------ | -------------------------------------- | -------- |
| All primitive types | The Symbol type is not included. | Yes | | All primitive types| The Symbol type is not included. | Yes |
| Date | | Yes | | Date | | Yes |
| String | | Yes | | String | | Yes |
| RegExp | | Yes | | RegExp | | Yes |
| Array | | Yes | | Array | | Yes |
| Map | | Yes | | Map | | Yes |
| Set | | Yes | | Set | | Yes |
| Object | Only plain objects are supported. Objects with functions are not supported. | Yes | | Object | Only plain objects are supported. Objects with functions are not supported.| Yes |
| ArrayBuffer | The transfer capability is provided. | Yes | | ArrayBuffer | The transfer capability is provided. | Yes |
| TypedArray | | Yes | | TypedArray | | Yes |
Exception: When an object created through a custom class is passed, no serialization error occurs. However, the attributes (such as Function) of the custom class cannot be passed through serialization. Exception: When an object created through a custom class is passed, no serialization error occurs. However, the attributes (such as Function) of the custom class cannot be passed through serialization.
> **NOTE**<br>
> An FA project of API version 9 is used as an example.
```js ```js
// main.js // main.js
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const workerInstance = new worker.Worker("workers/worker.js"); const workerInstance = new worker.Thread("workers/worker.js");
workerInstance.postMessage("message from main to worker"); workerInstance.postMessage("message from main to worker");
workerInstance.onmessage = function(d) { workerInstance.onmessage = function(d) {
// When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method. // When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method.
...@@ -719,7 +1412,7 @@ workerInstance.onmessage = function(d) { ...@@ -719,7 +1412,7 @@ workerInstance.onmessage = function(d) {
```js ```js
// worker.js // worker.js
import worker from '@ohos.worker'; import worker from '@ohos.worker';
const parentPort = worker.parentPort; const parentPort = worker.workerPort;
class MyModel { class MyModel {
Init() { Init() {
this.name = "wzy" this.name = "wzy"
...@@ -762,18 +1455,26 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther ...@@ -762,18 +1455,26 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther
### Precautions ### Precautions
- Currently, a maximum of seven workers can co-exist. - Currently, a maximum of seven workers can co-exist.
- If the number of workers exceeds the upper limit, the error message "Too many workers, the number of workers exceeds the maximum." is displayed. - In API version 8 and earlier versions, when the number of **Worker** instances exceeds the upper limit, the error "Too many workers, the number of workers exceeds the maximum." is thrown.
- Since API version 9, when the number of **Worker** instances exceeds the upper limit, the business error "Worker initialization failure, the number of workers exceeds the maximum" is thrown.
- To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance. - To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance.
- Since API version 9, if a **Worker** instance in a non-running state (such as destroyed or being destroyed) calls an API, a business error is thrown.
- Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them. - Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them.
## Sample Code ## Sample Code
> **NOTE**<br>
> Two projects of API version 9 are used as an example. <br>Only the FA model is supported in API version 8 and earlier versions. If you want to use API version 8 or earlier, change the API for constructing the **Worker** instance and the API for creating an object in the worker thread for communicating with the main thread.
### FA Model ### FA Model
```js ```js
// main.js (The following assumes that the worker script directory and pages directory are at the same level.) // main.js (The following assumes that the worker script directory and pages directory are at the same level.)
import worker from '@ohos.worker'; import worker from '@ohos.worker';
// Create a Worker instance in the main thread. // Create a Worker instance in the main thread.
const workerInstance = new worker.Worker("workers/worker.ts"); const workerInstance = new worker.ThreadWorker("workers/worker.ts");
// Create either a .json or .ts file. // Create either a .json or .ts file.
// const workerInstance = new worker.ThreadWorker("workers/worker.js");
// In versions earlier than API version 9, use the following to create a Worker instance in the main thread.
// const workerInstance = new worker.Worker("workers/worker.js"); // const workerInstance = new worker.Worker("workers/worker.js");
// The main thread transfers information to the worker thread. // The main thread transfers information to the worker thread.
...@@ -795,17 +1496,20 @@ workerInstance.onexit = function() { ...@@ -795,17 +1496,20 @@ workerInstance.onexit = function() {
} }
``` ```
```js ```js
// worker.js // worker.ts
import worker from '@ohos.worker'; import worker from '@ohos.worker';
// Create an object in the worker thread for communicating with the main thread. // Create an object in the worker thread for communicating with the main thread.
const parentPort = worker.parentPort const parentPort = worker.workerPort
// In versions earlier than API version 9, use the following to create an object in the worker thread for communicating with the main thread.
// const parentPort = worker.parentPort
// The worker thread receives information from the main thread. // The worker thread receives information from the main thread.
parentPort.onmessage = function(e) { parentPort.onmessage = function(e) {
// data carries the information sent by the main thread. // data carries the information sent by the main thread.
let data = e.data; let data = e.data;
console.log("worker.js onmessage"); console.log("worker.ts onmessage");
// The worker thread sends information to the main thread. // The worker thread sends information to the main thread.
parentPort.postMessage("123") parentPort.postMessage("123")
...@@ -813,7 +1517,7 @@ parentPort.onmessage = function(e) { ...@@ -813,7 +1517,7 @@ parentPort.onmessage = function(e) {
// Trigger a callback when an error occurs in the worker thread. // Trigger a callback when an error occurs in the worker thread.
parentPort.onerror= function(e) { parentPort.onerror= function(e) {
console.log("worker.js onerror"); console.log("worker.ts onerror");
} }
``` ```
Configuration of the **build-profile.json5** file: Configuration of the **build-profile.json5** file:
...@@ -832,9 +1536,9 @@ Configuration of the **build-profile.json5** file: ...@@ -832,9 +1536,9 @@ Configuration of the **build-profile.json5** file:
import worker from '@ohos.worker'; import worker from '@ohos.worker';
// Create a Worker instance in the main thread. // Create a Worker instance in the main thread.
const workerInstance = new worker.Worker("entry/ets/pages/workers/worker.ts"); const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.ts");
// Create either a .json or .ts file. // Create either a .json or .ts file.
// const workerInstance = new worker.Worker("entry/ets/pages/workers/worker.js"); // const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.js");
// The main thread transfers information to the worker thread. // The main thread transfers information to the worker thread.
workerInstance.postMessage("123"); workerInstance.postMessage("123");
...@@ -854,17 +1558,17 @@ workerInstance.onexit = function() { ...@@ -854,17 +1558,17 @@ workerInstance.onexit = function() {
} }
``` ```
```js ```js
// worker.js // worker.ts
import worker from '@ohos.worker'; import worker from '@ohos.worker';
// Create an object in the worker thread for communicating with the main thread. // Create an object in the worker thread for communicating with the main thread.
const parentPort = worker.parentPort const parentPort = worker.workerPort
// The worker thread receives information from the main thread. // The worker thread receives information from the main thread.
parentPort.onmessage = function(e) { parentPort.onmessage = function(e) {
// data carries the information sent by the main thread. // data carries the information sent by the main thread.
let data = e.data; let data = e.data;
console.log("worker.js onmessage"); console.log("worker.ts onmessage");
// The worker thread sends information to the main thread. // The worker thread sends information to the main thread.
parentPort.postMessage("123") parentPort.postMessage("123")
...@@ -872,7 +1576,7 @@ parentPort.onmessage = function(e) { ...@@ -872,7 +1576,7 @@ parentPort.onmessage = function(e) {
// Trigger a callback when an error occurs in the worker thread. // Trigger a callback when an error occurs in the worker thread.
parentPort.onerror= function(e) { parentPort.onerror= function(e) {
console.log("worker.js onerror"); console.log("worker.ts onerror");
} }
``` ```
Configuration of the **build-profile.json5** file: Configuration of the **build-profile.json5** file:
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册