js-apis-worker.md 52.5 KB
Newer Older
W
wusongqing 已提交
1
# Worker Startup
Z
zengyawen 已提交
2

G
Gloria 已提交
3 4
> **NOTE**
>
W
wusongqing 已提交
5
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Z
zengyawen 已提交
6

G
Gloria 已提交
7
The worker thread is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The URL file passed in during worker creation is executed in the worker thread. The worker thread can process time-consuming operations, but cannot directly operate the UI.
W
wusongqing 已提交
8 9

## Modules to Import
Z
zengyawen 已提交
10

G
Gloria 已提交
11
```js
Z
zengyawen 已提交
12 13 14
import worker from '@ohos.worker';
```

W
wusongqing 已提交
15 16 17

## Attributes

W
wusongqing 已提交
18 19
**System capability**: SystemCapability.Utils.Lang

G
Gloria 已提交
20 21 22 23
| Name                             | Type                                                 | Readable| Writable| Description                                                        |
| --------------------------------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| 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.|
W
wusongqing 已提交
24 25 26


## WorkerOptions
Z
zengyawen 已提交
27

W
wusongqing 已提交
28 29 30
Provides options that can be set for the **Worker** instance to create.

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
31

G
Gloria 已提交
32 33 34
| Name| Type| Readable| Writable| Description          |
| ---- | -------- | ---- | ---- | -------------- |
| name | string   | Yes  | Yes  | Name of the worker thread.|
W
wusongqing 已提交
35 36


G
Gloria 已提交
37
## ThreadWorker<sup>9+</sup>
W
wusongqing 已提交
38

G
Gloria 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
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
W
wusongqing 已提交
556

G
Gloria 已提交
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
**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).
W
wusongqing 已提交
663

G
Gloria 已提交
664 665 666
### 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.
W
wusongqing 已提交
667 668 669 670 671

constructor(scriptURL: string, options?: WorkerOptions)

A constructor used to create a **Worker** instance.

W
wusongqing 已提交
672 673
**System capability**: SystemCapability.Utils.Lang

W
wusongqing 已提交
674 675
**Parameters**

W
wusongqing 已提交
676 677
| Name   | Type                           | Mandatory| Description                                                        |
| --------- | ------------------------------- | ---- | ------------------------------------------------------------ |
G
Gloria 已提交
678
| 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.|
W
wusongqing 已提交
679
| options   | [WorkerOptions](#workeroptions) | No  | Options that can be set for the **Worker** instance.                                          |
W
wusongqing 已提交
680 681 682

**Return value**

W
wusongqing 已提交
683 684 685
| Type  | Description                                                     |
| ------ | --------------------------------------------------------- |
| Worker | Returns the **Worker** instance created; returns **undefined** if the **Worker** instance fails to be created.|
W
wusongqing 已提交
686 687 688

**Example**

G
Gloria 已提交
689
```js
690
import worker from '@ohos.worker';
691
// Create a Worker instance.
G
Gloria 已提交
692

693 694 695 696
// In the FA model, the worker script directory and pages directory are at the same level.
const workerFAModel01 = new worker.Worker("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.Worker("../workers/worker.js");
G
Gloria 已提交
697

698 699 700
// In the stage model, the worker script directory and pages directory are at the same level.
const workerStageModel01 = new worker.Worker('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.
701
const workerStageModel02 = new worker.Worker('entry/ets/pages/workers/worker.ts');
G
Gloria 已提交
702

703
// For the script URL "entry/ets/workers/worker.ts" in the stage model:
G
Gloria 已提交
704 705 706
// entry is the value of the name attribute under module in the module.json5 file.
// ets indicates the programming language in use.
```
707 708 709
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.
G
Gloria 已提交
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731

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"
      ]
    }
  }
```
732 733
(2) The worker script directory and **pages** directory are at different levels.

G
Gloria 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
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"
      ]
    }
  }
W
wusongqing 已提交
753
```
G
Gloria 已提交
754 755 756 757
### 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.
W
wusongqing 已提交
758 759

postMessage(message: Object, options?: PostMessageOptions): void
Z
zengyawen 已提交
760

761
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).
W
wusongqing 已提交
762 763

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
764

W
wusongqing 已提交
765 766
**Parameters**

W
wusongqing 已提交
767 768
| Name | Type                                     | Mandatory| Description                                                        |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
G
Gloria 已提交
769
| message | Object                                    | Yes  | Message to be sent to the worker thread.                                        |
W
wusongqing 已提交
770
| options | [PostMessageOptions](#postmessageoptions) | No  | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.|
W
wusongqing 已提交
771 772 773

**Example**

G
Gloria 已提交
774
```js
W
wusongqing 已提交
775
const workerInstance = new worker.Worker("workers/worker.js");
776

W
wusongqing 已提交
777
workerInstance.postMessage("hello world");
778

W
wusongqing 已提交
779 780 781 782 783
var buffer = new ArrayBuffer(8);
workerInstance.postMessage(buffer, [buffer]);
```


G
Gloria 已提交
784 785 786 787
### 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.
W
wusongqing 已提交
788 789

on(type: string, listener: EventListener): void
Z
zengyawen 已提交
790

791
Adds an event listener for the worker thread.
W
wusongqing 已提交
792 793

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
794

W
wusongqing 已提交
795 796
**Parameters**

W
wusongqing 已提交
797 798 799
| Name  | Type                           | Mandatory| Description            |
| -------- | ------------------------------- | ---- | ---------------- |
| type     | string                          | Yes  | Type of the event to listen for.|
G
Gloria 已提交
800
| listener | [EventListener](#eventlistener) | Yes  | Callback to invoke when an event of the specified type occurs.      |
W
wusongqing 已提交
801 802 803

**Example**

G
Gloria 已提交
804 805
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
806 807 808 809 810 811
workerInstance.on("alert", (e)=>{
    console.log("alert listener callback");
})
```


G
Gloria 已提交
812 813 814 815
### 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.
W
wusongqing 已提交
816 817

once(type: string, listener: EventListener): void
Z
zengyawen 已提交
818

G
Gloria 已提交
819
Adds an event listener for the worker thread and removes the event listener after it is invoked once.
W
wusongqing 已提交
820 821

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
822

W
wusongqing 已提交
823 824
**Parameters**

W
wusongqing 已提交
825 826 827
| Name  | Type                           | Mandatory| Description            |
| -------- | ------------------------------- | ---- | ---------------- |
| type     | string                          | Yes  | Type of the event to listen for.|
G
Gloria 已提交
828
| listener | [EventListener](#eventlistener) | Yes  | Callback to invoke when an event of the specified type occurs.      |
W
wusongqing 已提交
829 830 831

**Example**

G
Gloria 已提交
832
```js
W
wusongqing 已提交
833 834 835 836 837 838 839
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.once("alert", (e)=>{
    console.log("alert listener callback");
})
```


G
Gloria 已提交
840 841 842 843
### 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.
W
wusongqing 已提交
844 845

off(type: string, listener?: EventListener): void
Z
zengyawen 已提交
846

G
Gloria 已提交
847
Removes an event listener for the worker thread.
W
wusongqing 已提交
848 849

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
850

W
wusongqing 已提交
851 852
**Parameters**

G
Gloria 已提交
853 854 855 856
| Name  | Type                           | Mandatory| Description                |
| -------- | ------------------------------- | ---- | -------------------- |
| 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.    |
W
wusongqing 已提交
857 858 859

**Example**

G
Gloria 已提交
860
```js
W
wusongqing 已提交
861 862 863 864 865
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.off("alert");
```


G
Gloria 已提交
866 867 868 869
### 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.
W
wusongqing 已提交
870 871

terminate(): void
Z
zengyawen 已提交
872

G
Gloria 已提交
873
Terminates the worker thread to stop it from receiving messages.
W
wusongqing 已提交
874 875

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
876

W
wusongqing 已提交
877
**Example**
Z
zengyawen 已提交
878

G
Gloria 已提交
879 880 881
```js
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.terminate();
W
wusongqing 已提交
882
```
Z
zengyawen 已提交
883 884


G
Gloria 已提交
885 886 887 888
### 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.
Z
zengyawen 已提交
889

W
wusongqing 已提交
890
onexit?: (code: number) =&gt; void
Z
zengyawen 已提交
891

G
Gloria 已提交
892
Defines the event handler to be called when the worker thread exits. The handler is executed in the host thread.
W
wusongqing 已提交
893 894

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
895

W
wusongqing 已提交
896 897
**Parameters**

W
wusongqing 已提交
898 899
| Name| Type  | Mandatory| Description              |
| ------ | ------ | ---- | ------------------ |
G
Gloria 已提交
900
| code   | number | No  | Code indicating the worker thread exit state.|
W
wusongqing 已提交
901 902 903

**Example**

G
Gloria 已提交
904 905
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
906
workerInstance.onexit = function(e) {
G
Gloria 已提交
907
    console.log("onexit");
W
wusongqing 已提交
908 909 910 911
}
```


G
Gloria 已提交
912 913 914 915
### 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.
W
wusongqing 已提交
916 917

onerror?: (err: ErrorEvent) =&gt; void
Z
zengyawen 已提交
918

G
Gloria 已提交
919
Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread.
W
wusongqing 已提交
920 921

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
922

W
wusongqing 已提交
923 924
**Parameters**

W
wusongqing 已提交
925 926 927
| Name| Type                     | Mandatory| Description      |
| ------ | ------------------------- | ---- | ---------- |
| err    | [ErrorEvent](#errorevent) | No  | Error data.|
W
wusongqing 已提交
928 929 930

**Example**

G
Gloria 已提交
931 932
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
933
workerInstance.onerror = function(e) {
G
Gloria 已提交
934
    console.log("onerror");
W
wusongqing 已提交
935 936 937 938
}
```


G
Gloria 已提交
939 940 941 942
### 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.
W
wusongqing 已提交
943

944
onmessage?: (event: MessageEvent\<T>) =&gt; void
W
wusongqing 已提交
945

G
Gloria 已提交
946
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.
W
wusongqing 已提交
947 948

**System capability**: SystemCapability.Utils.Lang
W
wusongqing 已提交
949 950 951

**Parameters**

W
wusongqing 已提交
952 953 954
| Name| Type                         | Mandatory| Description                  |
| ------ | ----------------------------- | ---- | ---------------------- |
| event  | [MessageEvent](#messageevent) | No  | Message received.|
W
wusongqing 已提交
955 956 957

**Example**

G
Gloria 已提交
958 959
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
960
workerInstance.onmessage = function(e) {
G
Gloria 已提交
961 962 963
    // e: MessageEvent<T>. The usage is as follows:
    // let data = e.data;
    console.log("onmessage");
W
wusongqing 已提交
964 965 966 967
}
```


G
Gloria 已提交
968 969 970 971
### 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.
W
wusongqing 已提交
972

973
onmessageerror?: (event: MessageEvent\<T>) =&gt; void
Z
zengyawen 已提交
974

G
Gloria 已提交
975
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.
W
wusongqing 已提交
976 977

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
978

W
wusongqing 已提交
979 980
**Parameters**

W
wusongqing 已提交
981 982 983
| Name| Type                         | Mandatory| Description      |
| ------ | ----------------------------- | ---- | ---------- |
| event  | [MessageEvent](#messageevent) | No  | Error data.|
W
wusongqing 已提交
984 985 986

**Example**

G
Gloria 已提交
987 988
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
989
workerInstance.onmessageerror= function(e) {
G
Gloria 已提交
990
    console.log("onmessageerror");
W
wusongqing 已提交
991 992 993 994
}
```


G
Gloria 已提交
995 996 997
## 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.
W
wusongqing 已提交
998

G
Gloria 已提交
999
### addEventListener<sup>(deprecated)</sup>
W
wusongqing 已提交
1000

G
Gloria 已提交
1001 1002
> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [addEventListener<sup>9+</sup>](#addeventlistener9) instead.
W
wusongqing 已提交
1003 1004

addEventListener(type: string, listener: EventListener): void
Z
zengyawen 已提交
1005

G
Gloria 已提交
1006
Adds an event listener for the worker thread.
W
wusongqing 已提交
1007 1008

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1009

W
wusongqing 已提交
1010 1011
**Parameters**

W
wusongqing 已提交
1012 1013 1014 1015
| Name  | Type                           | Mandatory| Description            |
| -------- | ------------------------------- | ---- | ---------------- |
| 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.    |
W
wusongqing 已提交
1016 1017 1018

**Example**

G
Gloria 已提交
1019 1020
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1021 1022 1023 1024 1025 1026
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
```


G
Gloria 已提交
1027 1028 1029 1030
### 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.
W
wusongqing 已提交
1031 1032

removeEventListener(type: string, callback?: EventListener): void
Z
zengyawen 已提交
1033

G
Gloria 已提交
1034
Removes an event listener for the worker thread.
W
wusongqing 已提交
1035 1036

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1037

W
wusongqing 已提交
1038 1039
**Parameters**

G
Gloria 已提交
1040 1041
| Name  | Type                           | Mandatory| Description                    |
| -------- | ------------------------------- | ---- | ------------------------ |
1042
| type     | string                          | Yes  | Type of the event for which the event listener is to be removed.|
G
Gloria 已提交
1043
| callback | [EventListener](#eventlistener) | No  | Callback of the event listener to remove.        |
W
wusongqing 已提交
1044 1045 1046

**Example**

G
Gloria 已提交
1047 1048 1049
```js
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.removeEventListener("alert");
W
wusongqing 已提交
1050 1051 1052
```


G
Gloria 已提交
1053 1054 1055 1056
### 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.
W
wusongqing 已提交
1057 1058

dispatchEvent(event: Event): boolean
Z
zengyawen 已提交
1059

G
Gloria 已提交
1060
Dispatches the event defined for the worker thread.
W
wusongqing 已提交
1061 1062

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1063

W
wusongqing 已提交
1064 1065
**Parameters**

W
wusongqing 已提交
1066 1067 1068
| Name| Type           | Mandatory| Description            |
| ------ | --------------- | ---- | ---------------- |
| event  | [Event](#event) | Yes  | Event to dispatch.|
W
wusongqing 已提交
1069 1070 1071

**Return value**

W
wusongqing 已提交
1072 1073
| Type   | Description                           |
| ------- | ------------------------------- |
W
wusongqing 已提交
1074 1075 1076 1077
| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.|

**Example**

G
Gloria 已提交
1078 1079 1080
```js
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.dispatchEvent({type:"alert"});
W
wusongqing 已提交
1081 1082 1083
```


G
Gloria 已提交
1084 1085 1086 1087
### 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.
W
wusongqing 已提交
1088 1089

removeAllListener(): void
Z
zengyawen 已提交
1090

G
Gloria 已提交
1091
Removes all event listeners for the worker thread.
W
wusongqing 已提交
1092 1093

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1094

W
wusongqing 已提交
1095
**Example**
Z
zengyawen 已提交
1096

G
Gloria 已提交
1097 1098 1099
```js
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.removeAllListener();
W
wusongqing 已提交
1100
```
Z
zengyawen 已提交
1101 1102


G
Gloria 已提交
1103 1104 1105 1106
## 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.
Z
zengyawen 已提交
1107

1108
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).
Z
zengyawen 已提交
1109 1110


G
Gloria 已提交
1111 1112 1113 1114
### 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.
W
wusongqing 已提交
1115

G
Gloria 已提交
1116
postMessage(messageObject: Object, options?: PostMessageOptions): void
Z
zengyawen 已提交
1117

G
Gloria 已提交
1118
Sends a message to the host thread from the worker thread.
W
wusongqing 已提交
1119 1120

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1121

W
wusongqing 已提交
1122 1123
**Parameters**

W
wusongqing 已提交
1124 1125
| Name | Type                                     | Mandatory| Description                                                        |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
G
Gloria 已提交
1126
| message | Object                                    | Yes  | Message to be sent to the worker thread.                                      |
W
wusongqing 已提交
1127
| options | [PostMessageOptions](#postmessageoptions) | No  | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.|
W
wusongqing 已提交
1128 1129 1130

**Example**

G
Gloria 已提交
1131
```js
W
wusongqing 已提交
1132 1133
// main.js
import worker from '@ohos.worker';
G
Gloria 已提交
1134 1135
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.postMessage("hello world");
W
wusongqing 已提交
1136
workerInstance.onmessage = function(e) {
G
Gloria 已提交
1137 1138
    // let data = e.data;
    console.log("receive data from worker.js");
W
wusongqing 已提交
1139 1140
}
```
G
Gloria 已提交
1141
```js
W
wusongqing 已提交
1142 1143 1144 1145
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
parentPort.onmessage = function(e){
G
Gloria 已提交
1146 1147
    // let data = e.data;
    parentPort.postMessage("receive data from main.js");
W
wusongqing 已提交
1148 1149 1150 1151
}
```


G
Gloria 已提交
1152 1153 1154 1155
### 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.
W
wusongqing 已提交
1156 1157

close(): void
Z
zengyawen 已提交
1158

G
Gloria 已提交
1159
Terminates the worker thread to stop it from receiving messages.
W
wusongqing 已提交
1160 1161

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1162

W
wusongqing 已提交
1163 1164
**Example**

G
Gloria 已提交
1165
```js
W
wusongqing 已提交
1166 1167
// main.js
import worker from '@ohos.worker';
G
Gloria 已提交
1168
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1169
```
G
Gloria 已提交
1170
```js
W
wusongqing 已提交
1171 1172 1173 1174 1175 1176 1177 1178 1179
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
parentPort.onmessage = function(e) {
    parentPort.close()
}
```


G
Gloria 已提交
1180 1181 1182 1183
### 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.
W
wusongqing 已提交
1184

1185
onmessage?: (event: MessageEvent\<T>) =&gt; void
W
wusongqing 已提交
1186

1187
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.
W
wusongqing 已提交
1188 1189

**System capability**: SystemCapability.Utils.Lang
W
wusongqing 已提交
1190 1191 1192

**Parameters**

G
Gloria 已提交
1193 1194
| Name| Type                         | Mandatory| Description                    |
| ------ | ----------------------------- | ---- | ------------------------ |
W
wusongqing 已提交
1195
| event  | [MessageEvent](#messageevent) | No  | Message received.|
W
wusongqing 已提交
1196 1197 1198

**Example**

G
Gloria 已提交
1199
```js
W
wusongqing 已提交
1200 1201
// main.js
import worker from '@ohos.worker';
G
Gloria 已提交
1202 1203
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.postMessage("hello world");
W
wusongqing 已提交
1204
```
G
Gloria 已提交
1205
```js
W
wusongqing 已提交
1206 1207 1208 1209
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
parentPort.onmessage = function(e) {
G
Gloria 已提交
1210
    console.log("receive main.js message");
W
wusongqing 已提交
1211 1212 1213 1214
}
```


G
Gloria 已提交
1215 1216 1217 1218
### 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.
W
wusongqing 已提交
1219

1220
onmessageerror?: (event: MessageEvent\<T>) =&gt; void
Z
zengyawen 已提交
1221

G
Gloria 已提交
1222
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.
W
wusongqing 已提交
1223 1224

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1225

W
wusongqing 已提交
1226 1227
**Parameters**

W
wusongqing 已提交
1228 1229 1230
| Name| Type                         | Mandatory| Description      |
| ------ | ----------------------------- | ---- | ---------- |
| event  | [MessageEvent](#messageevent) | No  | Error data.|
W
wusongqing 已提交
1231 1232 1233

**Example**

G
Gloria 已提交
1234
```js
W
wusongqing 已提交
1235 1236
// main.js
import worker from '@ohos.worker';
G
Gloria 已提交
1237
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1238
```
G
Gloria 已提交
1239
```js
W
wusongqing 已提交
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
parentPort.onmessageerror= function(e) {
    console.log("worker.js onmessageerror")
}
```


## PostMessageOptions

Specifies the object whose ownership needs to be transferred during data transfer. The object must be **ArrayBuffer**.

W
wusongqing 已提交
1253 1254 1255 1256 1257
**System capability**: SystemCapability.Utils.Lang

| Name    | Type| Readable| Writable| Description                             |
| -------- | -------- | ---- | ---- | --------------------------------- |
| transfer | Object[] | Yes  | Yes  | **ArrayBuffer** array used to transfer the ownership.|
W
wusongqing 已提交
1258 1259 1260


## Event
Z
zengyawen 已提交
1261 1262 1263

Defines the event.

W
wusongqing 已提交
1264 1265 1266 1267 1268 1269
**System capability**: SystemCapability.Utils.Lang

| Name     | Type| Readable| Writable| Description                              |
| --------- | -------- | ---- | ---- | ---------------------------------- |
| type      | string   | Yes  | No  | Type of the event.                  |
| timeStamp | number   | Yes  | No  | Timestamp (accurate to millisecond) when the event is created.|
W
wusongqing 已提交
1270 1271


G
Gloria 已提交
1272 1273 1274 1275
## 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.
Z
zengyawen 已提交
1276

1277
(evt: Event): void | Promise&lt;void&gt;
Z
zengyawen 已提交
1278

1279
Implements event listening.
Z
zengyawen 已提交
1280

W
wusongqing 已提交
1281 1282
**System capability**: SystemCapability.Utils.Lang

W
wusongqing 已提交
1283 1284
**Parameters**

W
wusongqing 已提交
1285 1286 1287
| Name| Type           | Mandatory| Description          |
| ------ | --------------- | ---- | -------------- |
| evt    | [Event](#event) | Yes  | Event class for the callback to invoke.|
W
wusongqing 已提交
1288 1289 1290

**Return value**

W
wusongqing 已提交
1291 1292
| Type                                 | Description                           |
| ------------------------------------- | ------------------------------- |
W
wusongqing 已提交
1293 1294 1295 1296
| void&nbsp;\|&nbsp;Promise&lt;void&gt; | Returns no value or returns a **Promise**.|

**Example**

G
Gloria 已提交
1297
```js
W
wusongqing 已提交
1298 1299 1300 1301 1302 1303 1304 1305 1306
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
```


## ErrorEvent

G
Gloria 已提交
1307
Provides detailed information about the exception that occurs during worker execution. The **ErrorEvent** class inherits from [Event](#event).
W
wusongqing 已提交
1308 1309

**System capability**: SystemCapability.Utils.Lang
W
wusongqing 已提交
1310

W
wusongqing 已提交
1311 1312 1313 1314
| Name    | Type| Readable| Writable| Description                |
| -------- | -------- | ---- | ---- | -------------------- |
| message  | string   | Yes  | No  | Information about the exception.|
| filename | string   | Yes  | No  | File where the exception is located.|
G
Gloria 已提交
1315 1316
| lineno   | number   | Yes  | No  | Serial number of the line where the exception is located.    |
| colno    | number   | Yes  | No  | Serial number of the column where the exception is located.    |
W
wusongqing 已提交
1317
| error    | Object   | Yes  | No  | Type of the exception.          |
W
wusongqing 已提交
1318 1319 1320


## MessageEvent
Z
zengyawen 已提交
1321

G
Gloria 已提交
1322
Holds the data transferred between worker threads.
Z
zengyawen 已提交
1323

W
wusongqing 已提交
1324
**System capability**: SystemCapability.Utils.Lang
W
wusongqing 已提交
1325

W
wusongqing 已提交
1326 1327 1328
| Name| Type| Readable| Writable| Description              |
| ---- | -------- | ---- | ---- | ------------------ |
| data | T        | Yes  | No  | Data transferred between threads.|
W
wusongqing 已提交
1329 1330


G
Gloria 已提交
1331 1332 1333 1334
## 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.
W
wusongqing 已提交
1335

G
Gloria 已提交
1336
Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtarget).
W
wusongqing 已提交
1337 1338 1339

### Attributes

W
wusongqing 已提交
1340 1341
**System capability**: SystemCapability.Utils.Lang

G
Gloria 已提交
1342 1343
| Name| Type                                                    | Readable| Writable| Description                                 |
| ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- |
W
wusongqing 已提交
1344
| name | string                                                       | Yes  | No  | **Worker** instance specified when there is a new **Worker** instance.|
G
Gloria 已提交
1345
| self | [WorkerGlobalScope](#workerglobalscope)&nbsp;&amp;&nbsp;typeof&nbsp;globalThis | Yes  | No  | **WorkerGlobalScope**.              |
W
wusongqing 已提交
1346 1347


G
Gloria 已提交
1348 1349 1350 1351
### 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.
W
wusongqing 已提交
1352 1353

onerror?: (ev: ErrorEvent) =&gt; void
Z
zengyawen 已提交
1354

G
Gloria 已提交
1355
Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread.
W
wusongqing 已提交
1356 1357

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1358

W
wusongqing 已提交
1359
**Parameters**
Z
zengyawen 已提交
1360

W
wusongqing 已提交
1361 1362 1363
| Name| Type                     | Mandatory| Description      |
| ------ | ------------------------- | ---- | ---------- |
| ev     | [ErrorEvent](#errorevent) | No  | Error data.|
Z
zengyawen 已提交
1364

W
wusongqing 已提交
1365
**Example**
W
wusongqing 已提交
1366

G
Gloria 已提交
1367
```js
W
wusongqing 已提交
1368 1369 1370 1371
// main.js
import worker from '@ohos.worker';
const workerInstance = new worker.Worker("workers/worker.js")
```
G
Gloria 已提交
1372
```js
W
wusongqing 已提交
1373 1374 1375 1376 1377 1378 1379
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.parentPort
parentPort.onerror = function(e){
    console.log("worker.js onerror")
}
```
G
Gloria 已提交
1380

G
Gloria 已提交
1381

1382 1383 1384
## More Information

### Sequenceable Data Types
G
Gloria 已提交
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
| Type               | Remarks                                  | Supported|
| ------------------ | -------------------------------------- | -------- |
| All primitive types| The Symbol type is not included.                          | Yes      |
| Date               |                                        | Yes      |
| String             |                                        | Yes      |
| RegExp             |                                        | Yes      |
| Array              |                                        | Yes      |
| Map                |                                        | Yes      |
| Set                |                                        | Yes      |
| Object             | Only plain objects are supported. Objects with functions are not supported.| Yes      |
| ArrayBuffer        | The transfer capability is provided.                      | Yes      |
| TypedArray         |                                        | Yes      |
1397 1398

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.
G
Gloria 已提交
1399 1400 1401
> **NOTE**<br>
> An FA project of API version 9 is used as an example.

1402 1403 1404
```js
// main.js
import worker from '@ohos.worker';
G
Gloria 已提交
1405
const workerInstance = new worker.Thread("workers/worker.js");
1406 1407 1408 1409 1410 1411 1412 1413 1414
workerInstance.postMessage("message from main to worker");
workerInstance.onmessage = function(d) {
  // When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method.
  let data = d.data;
}
```
```js
// worker.js
import worker from '@ohos.worker';
G
Gloria 已提交
1415
const parentPort = worker.workerPort;
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
class MyModel {
    Init() {
        this.name = "wzy"
        this.age = 18
    }
    SetName() {
        this.name = "WZY"
    }
}
parentPort.onmessage = function(d) {
    console.log("worker.js onmessage");
    let data = d.data;
    let func1 = function() {
        console.log("post message is function");
    }
    let obj1 = {
        "index": 2,
        "name1": "zhangshan",
        setName() {
            this.index = 3;
        }
    }
    let obj2 = new MyModel();
    // parentPort.postMessage(func1); A serialization error occurs when passing func1.
    // parentPort.postMessage(obj1); A serialization error occurs when passing obj1.
    parentPort.postMessage(obj2);     // No serialization error occurs when passing obj2.
}
parentPort.onmessageerror = function(e) {
    console.log("worker.js onmessageerror");
}
parentPort.onerror = function(e) {
    console.log("worker.js onerror");
}
```

### Memory Model
The worker thread is implemented based on the actor model. In the worker interaction process, the JS main thread can create multiple worker threads, each of which are isolated and transfer data through sequentialization. They complete computing tasks and return the result to the main thread.

Each actor concurrently processes tasks of the main thread. For each actor, there is a message queue and a single-thread execution module. The message queue receives requests from the main thread and other actors; the single-thread execution module serially processes requests, sends requests to other actors, and creates new actors. These isolated actors use the asynchronous mode and can run concurrently.

### Precautions
- Currently, a maximum of seven workers can co-exist.
G
Gloria 已提交
1458 1459
- 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.
1460
- To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance.
G
Gloria 已提交
1461
- 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.
1462 1463
- Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them.

G
Gloria 已提交
1464
## Sample Code
G
Gloria 已提交
1465 1466
> **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.
G
Gloria 已提交
1467
### FA Model
G
Gloria 已提交
1468

G
Gloria 已提交
1469
```js
1470
// main.js (The following assumes that the worker script directory and pages directory are at the same level.)
G
Gloria 已提交
1471
import worker from '@ohos.worker';
1472
// Create a Worker instance in the main thread.
G
Gloria 已提交
1473
const workerInstance = new worker.ThreadWorker("workers/worker.ts");
G
Gloria 已提交
1474
// Create either a .json or .ts file.
G
Gloria 已提交
1475 1476 1477
// 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.
G
Gloria 已提交
1478 1479
// const workerInstance = new worker.Worker("workers/worker.js");

1480
// The main thread transfers information to the worker thread.
G
Gloria 已提交
1481
workerInstance.postMessage("123");
1482 1483

// The main thread receives information from the worker thread.
G
Gloria 已提交
1484
workerInstance.onmessage = function(e) {
1485
    // data carries the information sent by the worker thread.
G
Gloria 已提交
1486 1487
    let data = e.data;
    console.log("main.js onmessage");
1488 1489

    // Terminate the Worker instance.
G
Gloria 已提交
1490 1491
    workerInstance.terminate();
}
1492 1493

// Call onexit().
G
Gloria 已提交
1494 1495 1496 1497 1498
workerInstance.onexit = function() {
    console.log("main.js terminate");
}
```
```js
G
Gloria 已提交
1499
// worker.ts
G
Gloria 已提交
1500
import worker from '@ohos.worker';
1501 1502

// Create an object in the worker thread for communicating with the main thread.
G
Gloria 已提交
1503 1504 1505 1506
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
G
Gloria 已提交
1507

1508
// The worker thread receives information from the main thread.
G
Gloria 已提交
1509
parentPort.onmessage = function(e) {
1510
    // data carries the information sent by the main thread.
G
Gloria 已提交
1511
    let data = e.data;
G
Gloria 已提交
1512
    console.log("worker.ts onmessage");
1513 1514

    // The worker thread sends information to the main thread.
G
Gloria 已提交
1515 1516 1517
    parentPort.postMessage("123")
}

1518
// Trigger a callback when an error occurs in the worker thread.
G
Gloria 已提交
1519
parentPort.onerror= function(e) {
G
Gloria 已提交
1520
    console.log("worker.ts onerror");
G
Gloria 已提交
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
}
```
Configuration of the **build-profile.json5** file:
```json
  "buildOption": {
    "sourceOption": {
      "workers": [
        "./src/main/ets/MainAbility/workers/worker.ts"
      ]
    }
  }
```
### Stage Model
```js
1535
// main.js (The following assumes that the worker script directory and pages directory are at different levels.)
G
Gloria 已提交
1536
import worker from '@ohos.worker';
1537 1538

// Create a Worker instance in the main thread.
G
Gloria 已提交
1539
const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.ts");
G
Gloria 已提交
1540
// Create either a .json or .ts file.
G
Gloria 已提交
1541
// const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.js");
1542 1543

// The main thread transfers information to the worker thread.
G
Gloria 已提交
1544
workerInstance.postMessage("123");
1545 1546

// The main thread receives information from the worker thread.
G
Gloria 已提交
1547
workerInstance.onmessage = function(e) {
1548
    // data carries the information sent by the worker thread.
G
Gloria 已提交
1549 1550
    let data = e.data;
    console.log("main.js onmessage");
1551 1552

    // Terminate the Worker instance.
G
Gloria 已提交
1553 1554
    workerInstance.terminate();
}
1555
// Call onexit().
G
Gloria 已提交
1556 1557 1558 1559 1560
workerInstance.onexit = function() {
    console.log("main.js terminate");
}
```
```js
G
Gloria 已提交
1561
// worker.ts
G
Gloria 已提交
1562
import worker from '@ohos.worker';
1563 1564

// Create an object in the worker thread for communicating with the main thread.
G
Gloria 已提交
1565
const parentPort = worker.workerPort
G
Gloria 已提交
1566

1567
// The worker thread receives information from the main thread.
G
Gloria 已提交
1568
parentPort.onmessage = function(e) {
1569
    // data carries the information sent by the main thread.
G
Gloria 已提交
1570
    let data = e.data;
G
Gloria 已提交
1571
    console.log("worker.ts onmessage");
1572 1573

    // The worker thread sends information to the main thread.
G
Gloria 已提交
1574 1575 1576
    parentPort.postMessage("123")
}

1577
// Trigger a callback when an error occurs in the worker thread.
G
Gloria 已提交
1578
parentPort.onerror= function(e) {
G
Gloria 已提交
1579
    console.log("worker.ts onerror");
G
Gloria 已提交
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
}
```
Configuration of the **build-profile.json5** file:
```json
  "buildOption": {
    "sourceOption": {
      "workers": [
        "./src/main/ets/pages/workers/worker.ts"
      ]
    }
  }
```