js-apis-worker.md 77.8 KB
Newer Older
1
# @ohos.worker (Worker Startup)
2 3 4 5

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.

With the **Worker** module, you can provide a multithreading environment for an application, so that the application can perform a time-consuming operation in a background thread. This greatly prevents a computing-intensive or high-latency task from blocking the running of the main thread. A **Worker** instance will not be proactively destroyed once it is created. It consumes resources to keep running. Therefore, you should call the API to terminate it in a timely manner.
Z
zengyawen 已提交
6

7 8
The **Context** object of the worker thread is different from that of the main thread. The worker thread does not support UI operations.

G
Gloria 已提交
9 10
> **NOTE**
>
W
wusongqing 已提交
11
> 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 已提交
12

W
wusongqing 已提交
13
## Modules to Import
Z
zengyawen 已提交
14

G
Gloria 已提交
15
```js
Z
zengyawen 已提交
16 17 18
import worker from '@ohos.worker';
```

W
wusongqing 已提交
19 20 21

## Attributes

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

24
| Name                             | Type                                                     | Readable| Writable| Description                                                        |
G
Gloria 已提交
25 26
| --------------------------------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| workerPort<sup>9+</sup>           | [ThreadWorkerGlobalScope](#threadworkerglobalscope9)      | Yes  | Yes  | Object of the worker thread used to communicate with the host thread.                        |
27
| parentPort<sup>(deprecated)</sup> | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes  | Yes  | Object of the worker thread used to communicate with the host thread.<br>This attribute is supported since API version 7 and deprecated since API version 9.<br>You are advised to use **workerPort<sup>9+</sup>** instead.|
W
wusongqing 已提交
28 29 30


## WorkerOptions
Z
zengyawen 已提交
31

W
wusongqing 已提交
32 33 34
Provides options that can be set for the **Worker** instance to create.

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

G
Gloria 已提交
36 37
| Name| Type| Readable| Writable| Description          |
| ---- | -------- | ---- | ---- | -------------- |
38
| type | "classic" \| "module" | Yes  | Yes  | Mode in which the **Worker** instance executes the script. The default value is **classic**. The module **type** is not supported yet.|
G
Gloria 已提交
39
| name | string   | Yes  | Yes  | Name of the worker thread.|
40
| shared | boolean | Yes  | Yes  | Sharing of the **Worker** instance is not supported yet.|
W
wusongqing 已提交
41 42


G
Gloria 已提交
43
## ThreadWorker<sup>9+</sup>
W
wusongqing 已提交
44

45
Before using the following APIs, you must create a **ThreadWorker** instance. The **ThreadWorker** class inherits from [WorkerEventTarget](#workereventtarget9).
G
Gloria 已提交
46 47 48 49 50

### constructor<sup>9+</sup>

constructor(scriptURL: string, options?: WorkerOptions)

51
A constructor used to create a **ThreadWorker** instance.
G
Gloria 已提交
52 53 54 55 56 57 58 59 60 61 62 63

**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**

64 65 66 67 68 69 70 71 72 73 74 75 76 77
| Type        | Description                                                        |
| ------------ | ------------------------------------------------------------ |
| ThreadWorker | Returns the **ThreadWorker** instance created; returns **undefined** if the **ThreadWorker** instance fails to be created.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message|
| -------- | -------- |
| 10200003 | Worker initialization failure. |
| 10200007 | The worker file patch is invalid path. |


G
Gloria 已提交
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

**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": [
110
        "./src/main/ets/entryability/workers/worker.ts"
G
Gloria 已提交
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
      ]
    }
  }
```

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"
      ]
    }
  }
```

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
### postMessage<sup>9+</sup>

postMessage(message: Object, transfer: ArrayBuffer[]): 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.                                        |
| transfer | ArrayBuffer[] | Yes  | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                               |
| -------- | ----------------------------------------- |
| 10200004 | Worker instance is not running.           |
| 10200006 | Serializing an uncaught exception failed. |

**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");

workerInstance.postMessage("hello world");

var buffer = new ArrayBuffer(8);
workerInstance.postMessage(buffer, [buffer]);
```
G
Gloria 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

### 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**.|

204 205 206 207 208 209 210 211 212
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                               |
| -------- | ----------------------------------------- |
| 10200004 | Worker instance is not running.           |
| 10200006 | Serializing an uncaught exception failed. |

G
Gloria 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
**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

228
Adds an event listener for the worker thread. This API provides the same functionality as [addEventListener<sup>9+</sup>](#addeventlistener9).
G
Gloria 已提交
229 230 231 232 233 234 235 236 237 238

**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.|

239 240 241 242 243 244 245 246 247
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
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
**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.|

273 274 275 276 277 278 279 280 281
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295
**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

296
Removes an event listener for the worker thread. This API provides the same functionality as [removeEventListener<sup>9+</sup>](#removeeventlistener9).
G
Gloria 已提交
297 298 299 300 301 302 303 304 305 306

**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.|

307 308 309 310 311 312 313 314 315
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
316 317 318 319
**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
320
// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener.
G
Gloria 已提交
321 322 323 324 325 326 327 328 329 330 331 332
workerInstance.off("alert");
```


### terminate<sup>9+</sup>

terminate(): void

Terminates the worker thread to stop it from receiving messages.

**System capability**: SystemCapability.Utils.Lang

333 334 335 336 337 338 339 340
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

G
Gloria 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
**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              |
| ------ | ------ | ---- | ------------------ |
361
| code   | number | Yes  | Code indicating the worker thread exit state.|
G
Gloria 已提交
362

363 364 365 366 367 368 369 370 371
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
372 373 374 375 376 377 378
**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.onexit = function(e) {
    console.log("onexit");
}
379 380 381 382 383 384 385

// onexit is executed in either of the following ways:
// Main thread:
workerInstance.terminate();

// Worker thread:
//parentPort.close()
G
Gloria 已提交
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
```


### 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      |
| ------ | ------------------------- | ---- | ---------- |
401
| err    | [ErrorEvent](#errorevent) | Yes  | Error data.|
G
Gloria 已提交
402

403 404 405 406 407 408 409 410 411
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
412 413 414 415 416 417 418 419 420 421 422 423
**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.onerror = function(e) {
    console.log("onerror");
}
```


### onmessage<sup>9+</sup>

424
onmessage?: (event: MessageEvents) =&gt; void
G
Gloria 已提交
425 426 427 428 429 430 431

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**

432 433 434
| Name| Type                            | Mandatory| Description                  |
| ------ | -------------------------------- | ---- | ---------------------- |
| event  | [MessageEvents](#messageevents9) | Yes  | Message received.|
G
Gloria 已提交
435

436 437 438 439 440 441 442 443 444
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
445 446 447 448 449
**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.onmessage = function(e) {
450
    // e: MessageEvents. The usage is as follows:
G
Gloria 已提交
451 452 453 454 455 456 457 458
    // let data = e.data;
    console.log("onmessage");
}
```


### onmessageerror<sup>9+</sup>

459
onmessageerror?: (event: MessageEvents) =&gt; void
G
Gloria 已提交
460 461 462 463 464 465 466

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**

467 468 469
| Name| Type                            | Mandatory| Description      |
| ------ | -------------------------------- | ---- | ---------- |
| event  | [MessageEvents](#messageevents9) | Yes  | Error data.|
G
Gloria 已提交
470

471 472 473 474 475 476 477 478 479
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
480 481 482 483 484 485 486 487 488
**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.onmessageerror= function(e) {
    console.log("onmessageerror");
}
```

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 556 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
### addEventListener<sup>9+</sup>

addEventListener(type: string, listener: WorkerEventListener): void

Adds an event listener for the worker thread. This API provides the same functionality as [on<sup>9+</sup>](#on9).

**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.    |

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

**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. This API provides the same functionality as [off<sup>9+</sup>](#off9).

**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.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
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.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
// Usage 1:
workerInstance.on("alert_on", (e)=>{
    console.log("alert listener callback");
})
workerInstance.once("alert_once", (e)=>{
    console.log("alert listener callback");
})
workerInstance.addEventListener("alert_add", (e)=>{
    console.log("alert listener callback");
})

// The event listener created by once is removed after being executed once.
workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet.
// The event listener created by on will not be proactively deleted.
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
// The event listener created by addEventListener will be always valid and will not be proactively deleted.
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});

// Usage 2:
// The event type can be customized, and the special types "message", "messageerror", and "error" exist.
// When type = "message", the event handler defined by onmessage will also be executed.
// When type = "messageerror", the event handler defined by onmessageerror will also be executed.
// When type = "error", the event handler defined by onerror will also be executed.
// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once.

workerInstance.addEventListener("message", (e)=>{
    console.log("message listener callback");
})
workerInstance.onmessage = function(e) {
    console.log("onmessage : message listener callback");
}
// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked.
workerInstance.dispatchEvent({type:"message", timeStamp:0});
```


### removeAllListener<sup>9+</sup>

removeAllListener(): void

Removes all event listeners for the worker thread.

**System capability**: SystemCapability.Utils.Lang

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
workerInstance.removeAllListener();
```
G
Gloria 已提交
652 653 654 655 656 657 658

## WorkerEventTarget<sup>9+</sup>

### addEventListener<sup>9+</sup>

addEventListener(type: string, listener: WorkerEventListener): void

659
Adds an event listener for the worker thread. This API provides the same functionality as [on<sup>9+</sup>](#on9).
G
Gloria 已提交
660 661 662 663 664 665 666 667 668 669

**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.    |

670 671 672 673 674 675 676 677 678
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
679 680 681 682 683 684 685 686 687 688 689 690 691 692
**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

693
Removes an event listener for the worker thread. This API provides the same functionality as [off<sup>9+</sup>](#off9).
G
Gloria 已提交
694 695 696 697 698 699 700 701

**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.    |
702 703 704 705 706 707 708 709 710
| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. |

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |
G
Gloria 已提交
711 712 713 714 715

**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
716 717 718
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
G
Gloria 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
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.|

743 744 745 746 747 748 749 750
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

G
Gloria 已提交
751 752 753 754
**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
755 756 757 758 759 760 761 762 763 764 765 766
// Usage 1:
workerInstance.on("alert_on", (e)=>{
    console.log("alert listener callback");
})
workerInstance.once("alert_once", (e)=>{
    console.log("alert listener callback");
})
workerInstance.addEventListener("alert_add", (e)=>{
    console.log("alert listener callback");
})

// The event listener created by once is removed after being executed once.
767 768
workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet.
// The event listener created by on will not be proactively deleted.
769 770
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
771
// The event listener created by addEventListener will not be proactively deleted.
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});

// Usage 2:
// The event type can be customized, and the special types "message", "messageerror", and "error" exist.
// When type = "message", the event handler defined by onmessage will also be executed.
// When type = "messageerror", the event handler defined by onmessageerror will also be executed.
// When type = "error", the event handler defined by onerror will also be executed.
// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once.

workerInstance.addEventListener("message", (e)=>{
    console.log("message listener callback");
})
workerInstance.onmessage = function(e) {
    console.log("onmessage : message listener callback");
}
// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked.
workerInstance.dispatchEvent({type:"message", timeStamp:0});
G
Gloria 已提交
790 791 792 793 794 795 796 797 798 799 800
```


### removeAllListener<sup>9+</sup>

removeAllListener(): void

Removes all event listeners for the worker thread.

**System capability**: SystemCapability.Utils.Lang

801 802 803 804 805 806 807 808
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

G
Gloria 已提交
809 810 811 812
**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
813 814 815
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
G
Gloria 已提交
816 817 818 819 820 821
workerInstance.removeAllListener();
```


## ThreadWorkerGlobalScope<sup>9+</sup>

822
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 **ThreadWorkerGlobalScope** class inherits from [GlobalScope<sup>9+</sup>](#globalscope9).
G
Gloria 已提交
823

824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
### postMessage<sup>9+</sup>

postMessage(messageObject: Object, transfer: ArrayBuffer[]): 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.                                 |
| transfer | ArrayBuffer[] | Yes  | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                               |
| -------- | ----------------------------------------- |
| 10200004 | Worker instance is not running.           |
| 10200006 | Serializing an uncaught exception failed. |

**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 workerPort = worker.workerPort;
workerPort.onmessage = function(e){
    // let data = e.data;
    var buffer = new ArrayBuffer(8);
    workerPort.postMessage(buffer, [buffer]);
}
```
G
Gloria 已提交
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886

### 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**.|

887 888 889 890 891 892 893 894 895
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                               |
| -------- | ----------------------------------------- |
| 10200004 | Worker instance is not running.           |
| 10200006 | Serializing an uncaught exception failed. |

G
Gloria 已提交
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
**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';
912 913
const workerPort = worker.workerPort;
workerPort.onmessage = function(e){
G
Gloria 已提交
914
    // let data = e.data;
915
    workerPort.postMessage("receive data from main.js");
G
Gloria 已提交
916 917 918 919 920 921 922 923 924 925 926 927
}
```


### close<sup>9+</sup>

close(): void

Terminates the worker thread to stop it from receiving messages.

**System capability**: SystemCapability.Utils.Lang

928 929 930 931 932 933 934 935
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

G
Gloria 已提交
936 937 938 939 940 941 942 943 944 945 946
**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';
947 948 949
const workerPort = worker.workerPort;
workerPort.onmessage = function(e) {
    workerPort.close()
G
Gloria 已提交
950 951 952 953 954 955
}
```


### onmessage<sup>9+</sup>

956
onmessage?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) =&gt; void
G
Gloria 已提交
957 958 959 960 961 962 963

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**

964 965 966
| Name| Type                                                | Mandatory| Description                    |
| ------ | ---------------------------------------------------- | ---- | ------------------------ |
| this   | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes  | Caller.        |
967 968 969 970 971 972 973 974 975 976
| ev     | [MessageEvents](#messageevents9)                     | Yes  | Message received.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |
G
Gloria 已提交
977 978 979 980 981 982 983 984 985 986 987 988 989

**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';
990 991
const workerPort = worker.workerPort;
workerPort.onmessage = function(e) {
G
Gloria 已提交
992 993 994 995 996 997 998
    console.log("receive main.js message");
}
```


### onmessageerror<sup>9+</sup>

999
onmessageerror?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) =&gt; void
G
Gloria 已提交
1000 1001 1002 1003

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 已提交
1004

G
Gloria 已提交
1005 1006
**Parameters**

1007 1008 1009
| Name| Type                            | Mandatory| Description      |
| ------ | -------------------------------- | ---- | ---------- |
| this   | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes  | Caller.        |
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
| ev     | [MessageEvents](#messageevents9) | Yes  | Error data.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |
G
Gloria 已提交
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032

**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;
1033
parentPort.onmessageerror = function(e) {
G
Gloria 已提交
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    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**.|

1059 1060 1061 1062 1063 1064 1065 1066 1067
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
**Example**

```js
const workerInstance = new worker.ThreadWorker("workers/worker.js");
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
```


## GlobalScope<sup>9+</sup>

1080
Implements the running environment of the worker thread. The **GlobalScope** class inherits from [WorkerEventTarget](#workereventtarget9).
G
Gloria 已提交
1081 1082 1083 1084 1085

### Attributes

**System capability**: SystemCapability.Utils.Lang

1086
| Name| Type                                                        | Readable| Writable| Description                                 |
G
Gloria 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
| ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- |
| 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      |
| ------ | ------------------------- | ---- | ---------- |
1104
| ev     | [ErrorEvent](#errorevent) | Yes  | Error data.|
G
Gloria 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116

**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';
1117 1118
const workerPort = worker.workerPort
workerPort.onerror = function(e){
G
Gloria 已提交
1119 1120 1121 1122
    console.log("worker.js onerror")
}
```

1123 1124 1125 1126 1127 1128 1129 1130 1131
## MessageEvents<sup>9+</sup>

Holds the data transferred between worker threads.

**System capability**: SystemCapability.Utils.Lang

| Name| Type| Readable| Writable| Description              |
| ---- | ---- | ---- | ---- | ------------------ |
| data | any  | Yes  | No  | Data transferred between threads.|
G
Gloria 已提交
1132 1133 1134 1135 1136

## Worker<sup>(deprecated)</sup>


Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [EventTarget](#eventtarget).
W
wusongqing 已提交
1137

G
Gloria 已提交
1138
> **NOTE**<br>
1139 1140 1141
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker<sup>9+</sup>](#threadworker9) instead.

### constructor<sup>(deprecated)</sup>
W
wusongqing 已提交
1142 1143 1144 1145 1146

constructor(scriptURL: string, options?: WorkerOptions)

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

1147 1148 1149
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.constructor<sup>9+</sup>](#constructor9) instead.

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

W
wusongqing 已提交
1152 1153
**Parameters**

W
wusongqing 已提交
1154 1155
| Name   | Type                           | Mandatory| Description                                                        |
| --------- | ------------------------------- | ---- | ------------------------------------------------------------ |
G
Gloria 已提交
1156
| 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 已提交
1157
| options   | [WorkerOptions](#workeroptions) | No  | Options that can be set for the **Worker** instance.                                          |
W
wusongqing 已提交
1158 1159 1160

**Return value**

W
wusongqing 已提交
1161 1162 1163
| Type  | Description                                                     |
| ------ | --------------------------------------------------------- |
| Worker | Returns the **Worker** instance created; returns **undefined** if the **Worker** instance fails to be created.|
W
wusongqing 已提交
1164 1165 1166

**Example**

G
Gloria 已提交
1167
```js
1168
import worker from '@ohos.worker';
1169
// Create a Worker instance.
G
Gloria 已提交
1170

1171 1172 1173 1174
// 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 已提交
1175

1176 1177 1178
// 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.
1179
const workerStageModel02 = new worker.Worker('entry/ets/pages/workers/worker.ts');
G
Gloria 已提交
1180

1181
// For the script URL "entry/ets/workers/worker.ts" in the stage model:
G
Gloria 已提交
1182 1183 1184
// entry is the value of the name attribute under module in the module.json5 file.
// ets indicates the programming language in use.
```
1185 1186 1187
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 已提交
1188 1189 1190 1191 1192 1193 1194

In the FA model:

```json
  "buildOption": {
    "sourceOption": {
      "workers": [
1195
        "./src/main/ets/entryability/workers/worker.ts"
G
Gloria 已提交
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
      ]
    }
  }
```
In the stage model:
```json
  "buildOption": {
    "sourceOption": {
      "workers": [
        "./src/main/ets/workers/worker.ts"
      ]
    }
  }
```
1210 1211
(2) The worker script directory and **pages** directory are at different levels.

G
Gloria 已提交
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
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 已提交
1231
```
1232

G
Gloria 已提交
1233 1234
### postMessage<sup>(deprecated)</sup>

1235
postMessage(message: Object, transfer: ArrayBuffer[]): void;
Z
zengyawen 已提交
1236

1237
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 已提交
1238

1239 1240 1241
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage<sup>9+</sup>](#postmessage9) instead.

W
wusongqing 已提交
1242
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1243

W
wusongqing 已提交
1244 1245
**Parameters**

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
| Name  | Type         | Mandatory| Description                                           |
| -------- | ------------- | ---- | ----------------------------------------------- |
| message  | Object        | Yes  | Message to be sent to the worker thread.                           |
| transfer | ArrayBuffer[] | Yes  | **ArrayBuffer** instances that can be transferred.|

**Example**

```js
const workerInstance = new worker.Worker("workers/worker.js");

workerInstance.postMessage("hello world");

var buffer = new ArrayBuffer(8);
workerInstance.postMessage(buffer, [buffer]);
```

### postMessage<sup>(deprecated)</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).

> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage<sup>9+</sup>](#postmessage9-1) instead.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

W
wusongqing 已提交
1275 1276
| Name | Type                                     | Mandatory| Description                                                        |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
G
Gloria 已提交
1277
| message | Object                                    | Yes  | Message to be sent to the worker thread.                                        |
W
wusongqing 已提交
1278
| options | [PostMessageOptions](#postmessageoptions) | No  | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.|
W
wusongqing 已提交
1279 1280 1281

**Example**

G
Gloria 已提交
1282
```js
W
wusongqing 已提交
1283
const workerInstance = new worker.Worker("workers/worker.js");
1284

W
wusongqing 已提交
1285 1286 1287 1288
workerInstance.postMessage("hello world");
```


G
Gloria 已提交
1289 1290
### on<sup>(deprecated)</sup>

W
wusongqing 已提交
1291
on(type: string, listener: EventListener): void
Z
zengyawen 已提交
1292

1293 1294 1295 1296
Adds an event listener for the worker thread. This API provides the same functionality as [addEventListener<sup>(deprecated)</sup>](#addeventlistenerdeprecated).

> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.on<sup>9+</sup>](#on9) instead.
W
wusongqing 已提交
1297 1298

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

W
wusongqing 已提交
1300 1301
**Parameters**

W
wusongqing 已提交
1302 1303 1304
| Name  | Type                           | Mandatory| Description            |
| -------- | ------------------------------- | ---- | ---------------- |
| type     | string                          | Yes  | Type of the event to listen for.|
G
Gloria 已提交
1305
| listener | [EventListener](#eventlistener) | Yes  | Callback to invoke when an event of the specified type occurs.      |
W
wusongqing 已提交
1306 1307 1308

**Example**

G
Gloria 已提交
1309 1310
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1311 1312 1313 1314 1315 1316
workerInstance.on("alert", (e)=>{
    console.log("alert listener callback");
})
```


G
Gloria 已提交
1317 1318
### once<sup>(deprecated)</sup>

W
wusongqing 已提交
1319
once(type: string, listener: EventListener): void
Z
zengyawen 已提交
1320

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

1323 1324 1325
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.once<sup>9+</sup>](#once9) instead.

W
wusongqing 已提交
1326
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1327

W
wusongqing 已提交
1328 1329
**Parameters**

W
wusongqing 已提交
1330 1331 1332
| Name  | Type                           | Mandatory| Description            |
| -------- | ------------------------------- | ---- | ---------------- |
| type     | string                          | Yes  | Type of the event to listen for.|
G
Gloria 已提交
1333
| listener | [EventListener](#eventlistener) | Yes  | Callback to invoke when an event of the specified type occurs.      |
W
wusongqing 已提交
1334 1335 1336

**Example**

G
Gloria 已提交
1337
```js
W
wusongqing 已提交
1338 1339 1340 1341 1342 1343 1344
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.once("alert", (e)=>{
    console.log("alert listener callback");
})
```


G
Gloria 已提交
1345 1346
### off<sup>(deprecated)</sup>

W
wusongqing 已提交
1347
off(type: string, listener?: EventListener): void
Z
zengyawen 已提交
1348

1349 1350 1351 1352
Removes an event listener for the worker thread. This API provides the same functionality as [removeEventListener<sup>(deprecated)</sup>](#removeeventlistenerdeprecated).

> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.off<sup>9+</sup>](#off9) instead.
W
wusongqing 已提交
1353 1354

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

W
wusongqing 已提交
1356 1357
**Parameters**

G
Gloria 已提交
1358 1359 1360 1361
| 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 已提交
1362 1363 1364

**Example**

G
Gloria 已提交
1365
```js
W
wusongqing 已提交
1366
const workerInstance = new worker.Worker("workers/worker.js");
1367
// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener.
W
wusongqing 已提交
1368 1369 1370 1371
workerInstance.off("alert");
```


G
Gloria 已提交
1372 1373
### terminate<sup>(deprecated)</sup>

W
wusongqing 已提交
1374
terminate(): void
Z
zengyawen 已提交
1375

G
Gloria 已提交
1376
Terminates the worker thread to stop it from receiving messages.
W
wusongqing 已提交
1377

1378 1379 1380
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.terminate<sup>9+</sup>](#terminate9) instead.

W
wusongqing 已提交
1381
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1382

W
wusongqing 已提交
1383
**Example**
Z
zengyawen 已提交
1384

G
Gloria 已提交
1385 1386 1387
```js
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.terminate();
W
wusongqing 已提交
1388
```
Z
zengyawen 已提交
1389 1390


G
Gloria 已提交
1391 1392
### onexit<sup>(deprecated)</sup>

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

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

1397 1398 1399
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onexit<sup>9+</sup>](#onexit9) instead.

W
wusongqing 已提交
1400
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1401

W
wusongqing 已提交
1402 1403
**Parameters**

W
wusongqing 已提交
1404 1405
| Name| Type  | Mandatory| Description              |
| ------ | ------ | ---- | ------------------ |
1406
| code   | number | Yes  | Code indicating the worker thread exit state.|
W
wusongqing 已提交
1407 1408 1409

**Example**

G
Gloria 已提交
1410 1411
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1412
workerInstance.onexit = function(e) {
G
Gloria 已提交
1413
    console.log("onexit");
W
wusongqing 已提交
1414
}
1415 1416 1417 1418 1419 1420 1421

// onexit is executed in either of the following ways:
// Main thread:
workerInstance.terminate();

// Worker thread:
//parentPort.close()
W
wusongqing 已提交
1422 1423 1424
```


G
Gloria 已提交
1425 1426
### onerror<sup>(deprecated)</sup>

W
wusongqing 已提交
1427
onerror?: (err: ErrorEvent) =&gt; void
Z
zengyawen 已提交
1428

G
Gloria 已提交
1429
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 已提交
1430

1431 1432 1433
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onerror<sup>9+</sup>](#onerror9) instead.

W
wusongqing 已提交
1434
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1435

W
wusongqing 已提交
1436 1437
**Parameters**

W
wusongqing 已提交
1438 1439
| Name| Type                     | Mandatory| Description      |
| ------ | ------------------------- | ---- | ---------- |
1440
| err    | [ErrorEvent](#errorevent) | Yes  | Error data.|
W
wusongqing 已提交
1441 1442 1443

**Example**

G
Gloria 已提交
1444 1445
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1446
workerInstance.onerror = function(e) {
G
Gloria 已提交
1447
    console.log("onerror");
W
wusongqing 已提交
1448 1449 1450 1451
}
```


G
Gloria 已提交
1452 1453
### onmessage<sup>(deprecated)</sup>

1454
onmessage?: (event: MessageEvent) =&gt; void
W
wusongqing 已提交
1455

G
Gloria 已提交
1456
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 已提交
1457

1458 1459 1460
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onmessage<sup>9+</sup>](#onmessage9) instead.

W
wusongqing 已提交
1461
**System capability**: SystemCapability.Utils.Lang
W
wusongqing 已提交
1462 1463 1464

**Parameters**

1465 1466
| Name| Type                          | Mandatory| Description                  |
| ------ | ------------------------------ | ---- | ---------------------- |
1467
| event  | [MessageEvent](#messageevent)| Yes  | Message received.|
W
wusongqing 已提交
1468 1469 1470

**Example**

G
Gloria 已提交
1471 1472
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1473
workerInstance.onmessage = function(e) {
1474
    // e: MessageEvent. The usage is as follows:
G
Gloria 已提交
1475 1476
    // let data = e.data;
    console.log("onmessage");
W
wusongqing 已提交
1477 1478 1479 1480
}
```


G
Gloria 已提交
1481 1482
### onmessageerror<sup>(deprecated)</sup>

1483
onmessageerror?: (event: MessageEvent) =&gt; void
Z
zengyawen 已提交
1484

G
Gloria 已提交
1485
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 已提交
1486

1487 1488 1489
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onmessageerror<sup>9+</sup>](#onmessageerror9) instead.

W
wusongqing 已提交
1490
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1491

W
wusongqing 已提交
1492 1493
**Parameters**

1494 1495
| Name| Type                          | Mandatory| Description      |
| ------ | ------------------------------ | ---- | ---------- |
1496
| event  | [MessageEvent](#messageevent)| Yes  | Error data.|
W
wusongqing 已提交
1497 1498 1499

**Example**

G
Gloria 已提交
1500 1501
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1502
workerInstance.onmessageerror= function(e) {
G
Gloria 已提交
1503
    console.log("onmessageerror");
W
wusongqing 已提交
1504 1505 1506 1507
}
```


G
Gloria 已提交
1508 1509
## EventTarget<sup>(deprecated)</sup>
> **NOTE**<br>
1510
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [WorkerEventTarget<sup>9+</sup>](#workereventtarget9) instead.
W
wusongqing 已提交
1511

G
Gloria 已提交
1512
### addEventListener<sup>(deprecated)</sup>
W
wusongqing 已提交
1513 1514

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

1516 1517 1518 1519
Adds an event listener for the worker thread. This API provides the same functionality as [on<sup>(deprecated)</sup>](#ondeprecated).

> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addEventListener<sup>9+</sup>](#addeventlistener9) instead.
W
wusongqing 已提交
1520 1521

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

W
wusongqing 已提交
1523 1524
**Parameters**

W
wusongqing 已提交
1525 1526 1527 1528
| 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 已提交
1529 1530 1531

**Example**

G
Gloria 已提交
1532 1533
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1534 1535 1536 1537 1538 1539
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
```


G
Gloria 已提交
1540 1541
### removeEventListener<sup>(deprecated)</sup>

W
wusongqing 已提交
1542
removeEventListener(type: string, callback?: EventListener): void
Z
zengyawen 已提交
1543

1544 1545 1546 1547
Removes an event listener for the worker thread. This API provides the same functionality as [off<sup>(deprecated)</sup>](#offdeprecated).

> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeEventListener<sup>9+</sup>](#removeeventlistener9) instead.
W
wusongqing 已提交
1548 1549

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

W
wusongqing 已提交
1551 1552
**Parameters**

G
Gloria 已提交
1553 1554
| Name  | Type                           | Mandatory| Description                    |
| -------- | ------------------------------- | ---- | ------------------------ |
1555
| type     | string                          | Yes  | Type of the event for which the event listener is to be removed.|
G
Gloria 已提交
1556
| callback | [EventListener](#eventlistener) | No  | Callback of the event listener to remove.        |
W
wusongqing 已提交
1557 1558 1559

**Example**

G
Gloria 已提交
1560 1561
```js
const workerInstance = new worker.Worker("workers/worker.js");
1562 1563 1564
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
G
Gloria 已提交
1565
workerInstance.removeEventListener("alert");
W
wusongqing 已提交
1566 1567 1568
```


G
Gloria 已提交
1569 1570
### dispatchEvent<sup>(deprecated)</sup>

W
wusongqing 已提交
1571
dispatchEvent(event: Event): boolean
Z
zengyawen 已提交
1572

G
Gloria 已提交
1573
Dispatches the event defined for the worker thread.
W
wusongqing 已提交
1574

1575 1576 1577
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [dispatchEvent<sup>9+</sup>](#dispatchevent9) instead.

W
wusongqing 已提交
1578
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1579

W
wusongqing 已提交
1580 1581
**Parameters**

W
wusongqing 已提交
1582 1583 1584
| Name| Type           | Mandatory| Description            |
| ------ | --------------- | ---- | ---------------- |
| event  | [Event](#event) | Yes  | Event to dispatch.|
W
wusongqing 已提交
1585 1586 1587

**Return value**

W
wusongqing 已提交
1588 1589
| Type   | Description                           |
| ------- | ------------------------------- |
W
wusongqing 已提交
1590 1591 1592 1593
| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.|

**Example**

G
Gloria 已提交
1594 1595
```js
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1596

1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
// Usage 1:
workerInstance.on("alert_on", (e)=>{
    console.log("alert listener callback");
})
workerInstance.once("alert_once", (e)=>{
    console.log("alert listener callback");
})
workerInstance.addEventListener("alert_add", (e)=>{
    console.log("alert listener callback");
})
W
wusongqing 已提交
1607

1608
// The event listener created by once is removed after being executed once.
1609
workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet.
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
// The event listener created by on will not be proactively deleted.
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
// The event listener created by addEventListener will not be proactively deleted.
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});

// Usage 2:
// The event type can be customized, and the special types "message", "messageerror", and "error" exist.
// When type = "message", the event handler defined by onmessage will also be executed.
// When type = "messageerror", the event handler defined by onmessageerror will also be executed.
// When type = "error", the event handler defined by onerror will also be executed.
// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once.

workerInstance.addEventListener("message", (e)=>{
    console.log("message listener callback");
})
workerInstance.onmessage = function(e) {
    console.log("onmessage : message listener callback");
}
// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked.
workerInstance.dispatchEvent({type:"message", timeStamp:0});
```
G
Gloria 已提交
1633 1634
### removeAllListener<sup>(deprecated)</sup>

W
wusongqing 已提交
1635
removeAllListener(): void
Z
zengyawen 已提交
1636

G
Gloria 已提交
1637
Removes all event listeners for the worker thread.
W
wusongqing 已提交
1638

1639 1640 1641
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeAllListener<sup>9+</sup>](#removealllistener9) instead.

W
wusongqing 已提交
1642
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1643

W
wusongqing 已提交
1644
**Example**
Z
zengyawen 已提交
1645

G
Gloria 已提交
1646 1647
```js
const workerInstance = new worker.Worker("workers/worker.js");
1648 1649 1650
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
G
Gloria 已提交
1651
workerInstance.removeAllListener();
W
wusongqing 已提交
1652
```
Z
zengyawen 已提交
1653 1654


G
Gloria 已提交
1655 1656
## DedicatedWorkerGlobalScope<sup>(deprecated)</sup>

1657
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 已提交
1658

1659 1660
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>](#threadworkerglobalscope9) instead.
Z
zengyawen 已提交
1661

1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
### postMessage<sup>9+</sup>

postMessage(messageObject: Object, transfer: ArrayBuffer[]): 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.                               |
| transfer | ArrayBuffer[] | Yes  | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.|

**Example**

```js
// main.js
import worker from '@ohos.worker';
const workerInstance = new worker.Worker("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.parentPort;
parentPort.onmessage = function(e){
    // let data = e.data;
    let buffer = new ArrayBuffer(5)
    parentPort.postMessage(buffer, [buffer]);
}
```

G
Gloria 已提交
1700 1701
### postMessage<sup>(deprecated)</sup>

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

G
Gloria 已提交
1704
Sends a message to the host thread from the worker thread.
W
wusongqing 已提交
1705

1706 1707 1708
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>](#threadworkerglobalscope9).postMessage<sup>9+</sup> instead.

W
wusongqing 已提交
1709
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1710

W
wusongqing 已提交
1711 1712
**Parameters**

W
wusongqing 已提交
1713 1714
| Name | Type                                     | Mandatory| Description                                                        |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
G
Gloria 已提交
1715
| message | Object                                    | Yes  | Message to be sent to the worker thread.                                      |
W
wusongqing 已提交
1716
| options | [PostMessageOptions](#postmessageoptions) | No  | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.|
W
wusongqing 已提交
1717 1718 1719

**Example**

G
Gloria 已提交
1720
```js
W
wusongqing 已提交
1721 1722
// main.js
import worker from '@ohos.worker';
G
Gloria 已提交
1723 1724
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.postMessage("hello world");
W
wusongqing 已提交
1725
workerInstance.onmessage = function(e) {
G
Gloria 已提交
1726 1727
    // let data = e.data;
    console.log("receive data from worker.js");
W
wusongqing 已提交
1728 1729
}
```
G
Gloria 已提交
1730
```js
W
wusongqing 已提交
1731 1732 1733 1734
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
parentPort.onmessage = function(e){
G
Gloria 已提交
1735 1736
    // let data = e.data;
    parentPort.postMessage("receive data from main.js");
W
wusongqing 已提交
1737 1738 1739
}
```

G
Gloria 已提交
1740 1741
### close<sup>(deprecated)</sup>

W
wusongqing 已提交
1742
close(): void
Z
zengyawen 已提交
1743

G
Gloria 已提交
1744
Terminates the worker thread to stop it from receiving messages.
W
wusongqing 已提交
1745

1746 1747 1748
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>](#threadworkerglobalscope9).close<sup>9+</sup> instead.

W
wusongqing 已提交
1749
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1750

W
wusongqing 已提交
1751 1752
**Example**

G
Gloria 已提交
1753
```js
W
wusongqing 已提交
1754 1755
// main.js
import worker from '@ohos.worker';
G
Gloria 已提交
1756
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1757
```
G
Gloria 已提交
1758
```js
W
wusongqing 已提交
1759 1760 1761 1762 1763 1764 1765 1766 1767
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
parentPort.onmessage = function(e) {
    parentPort.close()
}
```


G
Gloria 已提交
1768 1769
### onmessage<sup>(deprecated)</sup>

1770
onmessage?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) =&gt; void
W
wusongqing 已提交
1771

1772
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 已提交
1773

1774 1775 1776
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>](#threadworkerglobalscope9).onmessage<sup>9+</sup> instead.

W
wusongqing 已提交
1777
**System capability**: SystemCapability.Utils.Lang
W
wusongqing 已提交
1778 1779 1780

**Parameters**

1781 1782 1783
| Name| Type                                                        | Mandatory| Description                    |
| ------ | ------------------------------------------------------------ | ---- | ------------------------ |
| this   | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes  | Caller.        |
1784
| ev     | [MessageEvent](#messageevent)                              | Yes  | Message received.|
W
wusongqing 已提交
1785 1786 1787

**Example**

G
Gloria 已提交
1788
```js
W
wusongqing 已提交
1789 1790
// main.js
import worker from '@ohos.worker';
G
Gloria 已提交
1791 1792
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.postMessage("hello world");
W
wusongqing 已提交
1793
```
G
Gloria 已提交
1794
```js
W
wusongqing 已提交
1795 1796 1797 1798
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
parentPort.onmessage = function(e) {
G
Gloria 已提交
1799
    console.log("receive main.js message");
W
wusongqing 已提交
1800 1801 1802 1803
}
```


G
Gloria 已提交
1804 1805
### onmessageerror<sup>(deprecated)</sup>

1806
onmessageerror?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) =&gt; void
Z
zengyawen 已提交
1807

G
Gloria 已提交
1808
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 已提交
1809

1810 1811 1812
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>](#threadworkerglobalscope9).onmessageerror<sup>9+</sup> instead.

W
wusongqing 已提交
1813
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1814

W
wusongqing 已提交
1815 1816
**Parameters**

1817 1818 1819
| Name| Type                          | Mandatory| Description      |
| ------ | ------------------------------ | ---- | ---------- |
| this   | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes  | Caller.|
1820
| ev     | [MessageEvent](#messageevent)| Yes  | Error data.|
W
wusongqing 已提交
1821 1822 1823

**Example**

G
Gloria 已提交
1824
```js
W
wusongqing 已提交
1825 1826
// main.js
import worker from '@ohos.worker';
G
Gloria 已提交
1827
const workerInstance = new worker.Worker("workers/worker.js");
W
wusongqing 已提交
1828
```
G
Gloria 已提交
1829
```js
W
wusongqing 已提交
1830 1831 1832
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
1833
parentPort.onmessageerror = function(e) {
W
wusongqing 已提交
1834 1835 1836 1837 1838 1839 1840 1841 1842
    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 已提交
1843 1844
**System capability**: SystemCapability.Utils.Lang

1845
| Name    | Type    | Readable| Writable| Description                             |
W
wusongqing 已提交
1846 1847
| -------- | -------- | ---- | ---- | --------------------------------- |
| transfer | Object[] | Yes  | Yes  | **ArrayBuffer** array used to transfer the ownership.|
W
wusongqing 已提交
1848 1849 1850


## Event
Z
zengyawen 已提交
1851 1852 1853

Defines the event.

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

1856 1857 1858 1859
| 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. This parameter is not supported yet.|
W
wusongqing 已提交
1860 1861


G
Gloria 已提交
1862 1863
## EventListener<sup>(deprecated)</sup>

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

1866
Implements event listening.
Z
zengyawen 已提交
1867

1868 1869 1870
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [WorkerEventListener<sup>9+</sup>](#workereventlistener9) instead.

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

W
wusongqing 已提交
1873 1874
**Parameters**

W
wusongqing 已提交
1875 1876 1877
| Name| Type           | Mandatory| Description          |
| ------ | --------------- | ---- | -------------- |
| evt    | [Event](#event) | Yes  | Event class for the callback to invoke.|
W
wusongqing 已提交
1878 1879 1880

**Return value**

W
wusongqing 已提交
1881 1882
| Type                                 | Description                           |
| ------------------------------------- | ------------------------------- |
W
wusongqing 已提交
1883 1884 1885 1886
| void&nbsp;\|&nbsp;Promise&lt;void&gt; | Returns no value or returns a **Promise**.|

**Example**

G
Gloria 已提交
1887
```js
W
wusongqing 已提交
1888 1889 1890 1891 1892 1893 1894 1895 1896
const workerInstance = new worker.Worker("workers/worker.js");
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
```


## ErrorEvent

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

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

1901 1902 1903 1904 1905 1906 1907
| Name    | Type  | Readable| Writable| Description                |
| -------- | ------ | ---- | ---- | -------------------- |
| message  | string | Yes  | No  | Information about the exception.|
| filename | string | Yes  | No  | File where the exception is located.|
| 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.    |
| error    | Object | Yes  | No  | Type of the exception.          |
W
wusongqing 已提交
1908 1909


1910
## MessageEvent\<T\>
Z
zengyawen 已提交
1911

G
Gloria 已提交
1912
Holds the data transferred between worker threads.
Z
zengyawen 已提交
1913

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

W
wusongqing 已提交
1916
| Name| Type| Readable| Writable| Description              |
1917 1918
| ---- | ---- | ---- | ---- | ------------------ |
| data | T    | Yes  | No  | Data transferred between threads.|
W
wusongqing 已提交
1919 1920


G
Gloria 已提交
1921 1922
## WorkerGlobalScope<sup>(deprecated)</sup>

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

1925 1926 1927
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope<sup>9+</sup>](#globalscope9) instead.

W
wusongqing 已提交
1928 1929
### Attributes

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

1932
| Name| Type                                                        | Readable| Writable| Description                                 |
G
Gloria 已提交
1933
| ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- |
W
wusongqing 已提交
1934
| name | string                                                       | Yes  | No  | **Worker** instance specified when there is a new **Worker** instance.|
G
Gloria 已提交
1935
| self | [WorkerGlobalScope](#workerglobalscope)&nbsp;&amp;&nbsp;typeof&nbsp;globalThis | Yes  | No  | **WorkerGlobalScope**.              |
W
wusongqing 已提交
1936 1937


G
Gloria 已提交
1938 1939
### onerror<sup>(deprecated)</sup>

W
wusongqing 已提交
1940
onerror?: (ev: ErrorEvent) =&gt; void
Z
zengyawen 已提交
1941

G
Gloria 已提交
1942
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 已提交
1943

1944 1945 1946
> **NOTE**<br>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope<sup>9+</sup>](#globalscope9).onerror instead.

W
wusongqing 已提交
1947
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1948

W
wusongqing 已提交
1949
**Parameters**
Z
zengyawen 已提交
1950

W
wusongqing 已提交
1951 1952
| Name| Type                     | Mandatory| Description      |
| ------ | ------------------------- | ---- | ---------- |
1953
| ev     | [ErrorEvent](#errorevent) | Yes  | Error data.|
Z
zengyawen 已提交
1954

W
wusongqing 已提交
1955
**Example**
W
wusongqing 已提交
1956

G
Gloria 已提交
1957
```js
W
wusongqing 已提交
1958 1959 1960 1961
// main.js
import worker from '@ohos.worker';
const workerInstance = new worker.Worker("workers/worker.js")
```
G
Gloria 已提交
1962
```js
W
wusongqing 已提交
1963 1964 1965 1966 1967 1968 1969
// worker.js
import worker from '@ohos.worker';
const parentPort = worker.parentPort
parentPort.onerror = function(e){
    console.log("worker.js onerror")
}
```
G
Gloria 已提交
1970

G
Gloria 已提交
1971

1972 1973 1974
## More Information

### Sequenceable Data Types
G
Gloria 已提交
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
| 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      |
1987 1988

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 已提交
1989 1990 1991
> **NOTE**<br>
> An FA project of API version 9 is used as an example.

1992 1993 1994
```js
// main.js
import worker from '@ohos.worker';
1995
const workerInstance = new worker.ThreadWorker("workers/worker.js");
1996 1997 1998 1999 2000 2001 2002 2003 2004
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';
2005
const workerPort = worker.workerPort;
2006
class MyModel {
2007
    name = "undefined"
2008
    Init() {
2009
        this.name = "MyModel"
2010 2011
    }
}
2012
workerPort.onmessage = function(d) {
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
    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();
2026 2027 2028
    // workerPort.postMessage(func1); A serialization error occurs when passing func1.
    // workerPort.postMessage(obj1); A serialization error occurs when passing obj1.
    workerPort.postMessage(obj2);     // No serialization error occurs when passing obj2.
2029
}
2030
workerPort.onmessageerror = function(e) {
2031 2032
    console.log("worker.js onmessageerror");
}
2033
workerPort.onerror = function(e) {
2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
    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 已提交
2045 2046
- 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.
2047
- To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance.
G
Gloria 已提交
2048
- 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.
2049
- Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them.
2050
- Do not use both **new worker.Worker** and **new worker.ThreadWorker** to create a **Worker** project. Otherwise, **Worker** functions abnormally. Since API version 9, you are advised to use [new worker.ThreadWorker](#constructor9). In API version 8 and earlier versions, you are advised to use [new worker.Worker](#constructordeprecated).
2051
- When creating a **Worker** project, do not import any UI construction method (such as .ets file) to the worker thread file (for example, **worker.ts** used in this document). Otherwise, the worker module becomes invalid. To check whether any UI construction method has been imported, decompress the generated HAP file, find **worker.js** in the directory where the worker thread is created, and search for the keyword **View** globally. If the keyword exists, a UI construction method has been packaged in **worker.js**. If this is your case, change the directory level of **src** in the statement **import "xxx" from src** in the worker thread file.
2052

G
Gloria 已提交
2053
## Sample Code
G
Gloria 已提交
2054 2055
> **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 已提交
2056
### FA Model
G
Gloria 已提交
2057

G
Gloria 已提交
2058
```js
2059
// main.js (The following assumes that the worker script directory and pages directory are at the same level.)
G
Gloria 已提交
2060
import worker from '@ohos.worker';
2061
// Create a Worker instance in the main thread.
G
Gloria 已提交
2062
const workerInstance = new worker.ThreadWorker("workers/worker.ts");
G
Gloria 已提交
2063
// Create either a .json or .ts file.
G
Gloria 已提交
2064 2065 2066
// 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 已提交
2067 2068
// const workerInstance = new worker.Worker("workers/worker.js");

2069
// The main thread transfers information to the worker thread.
G
Gloria 已提交
2070
workerInstance.postMessage("123");
2071 2072

// The main thread receives information from the worker thread.
G
Gloria 已提交
2073
workerInstance.onmessage = function(e) {
2074
    // data carries the information sent by the worker thread.
G
Gloria 已提交
2075 2076
    let data = e.data;
    console.log("main.js onmessage");
2077 2078

    // Terminate the Worker instance.
G
Gloria 已提交
2079 2080
    workerInstance.terminate();
}
2081 2082

// Call onexit().
G
Gloria 已提交
2083 2084 2085 2086 2087
workerInstance.onexit = function() {
    console.log("main.js terminate");
}
```
```js
G
Gloria 已提交
2088
// worker.ts
G
Gloria 已提交
2089
import worker from '@ohos.worker';
2090 2091

// Create an object in the worker thread for communicating with the main thread.
2092
const workerPort = worker.workerPort
G
Gloria 已提交
2093 2094 2095

// 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 已提交
2096

2097
// The worker thread receives information from the main thread.
2098
workerPort.onmessage = function(e) {
2099
    // data carries the information sent by the main thread.
G
Gloria 已提交
2100
    let data = e.data;
G
Gloria 已提交
2101
    console.log("worker.ts onmessage");
2102 2103

    // The worker thread sends information to the main thread.
2104
    workerPort.postMessage("123")
G
Gloria 已提交
2105 2106
}

2107
// Trigger a callback when an error occurs in the worker thread.
2108
workerPort.onerror= function(e) {
G
Gloria 已提交
2109
    console.log("worker.ts onerror");
G
Gloria 已提交
2110 2111 2112 2113 2114 2115 2116
}
```
Configuration of the **build-profile.json5** file:
```json
  "buildOption": {
    "sourceOption": {
      "workers": [
2117
        "./src/main/ets/entryability/workers/worker.ts"
G
Gloria 已提交
2118 2119 2120 2121 2122 2123
      ]
    }
  }
```
### Stage Model
```js
2124
// main.js (The following assumes that the worker script directory and pages directory are at different levels.)
G
Gloria 已提交
2125
import worker from '@ohos.worker';
2126 2127

// Create a Worker instance in the main thread.
G
Gloria 已提交
2128
const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.ts");
G
Gloria 已提交
2129
// Create either a .json or .ts file.
G
Gloria 已提交
2130
// const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.js");
2131 2132

// The main thread transfers information to the worker thread.
G
Gloria 已提交
2133
workerInstance.postMessage("123");
2134 2135

// The main thread receives information from the worker thread.
G
Gloria 已提交
2136
workerInstance.onmessage = function(e) {
2137
    // data carries the information sent by the worker thread.
G
Gloria 已提交
2138 2139
    let data = e.data;
    console.log("main.js onmessage");
2140 2141

    // Terminate the Worker instance.
G
Gloria 已提交
2142 2143
    workerInstance.terminate();
}
2144
// Call onexit().
G
Gloria 已提交
2145 2146 2147 2148 2149
workerInstance.onexit = function() {
    console.log("main.js terminate");
}
```
```js
G
Gloria 已提交
2150
// worker.ts
G
Gloria 已提交
2151
import worker from '@ohos.worker';
2152 2153

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

2156
// The worker thread receives information from the main thread.
2157
workerPort.onmessage = function(e) {
2158
    // data carries the information sent by the main thread.
G
Gloria 已提交
2159
    let data = e.data;
G
Gloria 已提交
2160
    console.log("worker.ts onmessage");
2161 2162

    // The worker thread sends information to the main thread.
2163
    workerPort.postMessage("123")
G
Gloria 已提交
2164 2165
}

2166
// Trigger a callback when an error occurs in the worker thread.
2167
workerPort.onerror= function(e) {
G
Gloria 已提交
2168
    console.log("worker.ts onerror");
G
Gloria 已提交
2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180
}
```
Configuration of the **build-profile.json5** file:
```json
  "buildOption": {
    "sourceOption": {
      "workers": [
        "./src/main/ets/pages/workers/worker.ts"
      ]
    }
  }
```
2181
<!--no_check-->