• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Worker Startup
2
3> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
4> 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.
5
6A Worker thread is an independent thread running in parallel with the main thread. The thread that creates the Worker thread is referred to as a 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.
7
8## Modules to Import
9
10```
11import worker from '@ohos.worker';
12```
13
14
15## Attributes
16
17**System capability**: SystemCapability.Utils.Lang
18
19| Name      | Type                                                 | Readable| Writable| Description                                |
20| ---------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------ |
21| parentPort | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes  | Yes  | Object of the Worker thread used to communicate with the host thread.|
22
23
24## WorkerOptions
25
26Provides options that can be set for the **Worker** instance to create.
27
28**System capability**: SystemCapability.Utils.Lang
29
30| Name| Type | Readable| Writable| Description                  |
31| ---- | --------- | ---- | ---- | ---------------------- |
32| type | "classic" | Yes  | Yes  | Mode in which the Worker thread executes the script.|
33| name | string    | Yes  | Yes  | Name of the Worker thread.        |
34
35
36## Worker
37
38Before using the following APIs, you must construct a **Worker** instance. The **Worker** class inherits from [EventTarget](#eventtarget).
39
40
41### constructor
42
43constructor(scriptURL: string, options?: WorkerOptions)
44
45A constructor used to create a **Worker** instance.
46
47**System capability**: SystemCapability.Utils.Lang
48
49**Parameters**
50
51| Name   | Type                           | Mandatory| Description                                                        |
52| --------- | ------------------------------- | ---- | ------------------------------------------------------------ |
53| scriptURL | string                          | Yes  | URL of the script to be executed by the Worker thread. The script is stored in the **workers** directory, which is in the same directory as the **pages** directory of the new DevEco Studio project. If the **workers** directory does not exist, you need to create it.|
54| options   | [WorkerOptions](#workeroptions) | No  | Options that can be set for the **Worker** instance.                                          |
55
56**Return value**
57
58| Type  | Description                                                     |
59| ------ | --------------------------------------------------------- |
60| Worker | Returns the **Worker** instance created; returns **undefined** if the **Worker** instance fails to be created.|
61
62**Example**
63
64```
65const workerInstance = new worker.Worker("workers/worker.js", {name:"first worker"});
66```
67
68
69### postMessage
70
71postMessage(message: Object, options?: PostMessageOptions): void
72
73Sends a message to the Worker thread. The data is transferred using the structured clone algorithm.
74
75**System capability**: SystemCapability.Utils.Lang
76
77**Parameters**
78
79| Name | Type                                     | Mandatory| Description                                                        |
80| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
81| message | Object                                    | Yes  | Data to be sent to the Worker thread.                                        |
82| options | [PostMessageOptions](#postmessageoptions) | No  | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.|
83
84**Example**
85
86```
87const workerInstance = new worker.Worker("workers/worker.js");
88workerInstance.postMessage("hello world");
89```
90
91```
92const workerInstance= new worker.Worker("workers/worker.js");
93var buffer = new ArrayBuffer(8);
94workerInstance.postMessage(buffer, [buffer]);
95```
96
97
98### on
99
100on(type: string, listener: EventListener): void
101
102Adds an event listener for the Worker instance.
103
104**System capability**: SystemCapability.Utils.Lang
105
106**Parameters**
107
108| Name  | Type                           | Mandatory| Description            |
109| -------- | ------------------------------- | ---- | ---------------- |
110| type     | string                          | Yes  | Type of the event to listen for.|
111| listener | [EventListener](#eventlistener) | Yes  | Callback to invoke when an event of the specified type occurs.    |
112
113**Example**
114
115```
116const workerInstance = new worker.Worker("workers/worker.js")
117workerInstance.on("alert", (e)=>{
118    console.log("alert listener callback");
119})
120```
121
122
123### once
124
125once(type: string, listener: EventListener): void
126
127Adds an event listener for the Worker thread and removes the event listener after it is invoked once.
128
129**System capability**: SystemCapability.Utils.Lang
130
131**Parameters**
132
133| Name  | Type                           | Mandatory| Description            |
134| -------- | ------------------------------- | ---- | ---------------- |
135| type     | string                          | Yes  | Type of the event to listen for.|
136| listener | [EventListener](#eventlistener) | Yes  | Callback to invoke when an event of the specified type occurs.    |
137
138**Example**
139
140```
141const workerInstance = new worker.Worker("workers/worker.js");
142workerInstance.once("alert", (e)=>{
143    console.log("alert listener callback");
144})
145```
146
147
148### off
149
150off(type: string, listener?: EventListener): void
151
152Removes an event listener for the Worker thread.
153
154**System capability**: SystemCapability.Utils.Lang
155
156**Parameters**
157
158| Name  | Type                           | Mandatory| Description                  |
159| -------- | ------------------------------- | ---- | ---------------------- |
160| type     | string                          | Yes  | Type of the event for which the event listener is removed.  |
161| listener | [EventListener](#eventlistener) | No  | Callback of the event listener to remove.|
162
163**Example**
164
165```
166const workerInstance = new worker.Worker("workers/worker.js");
167workerInstance.off("alert");
168```
169
170
171### terminate
172
173terminate(): void
174
175Terminates the Worker thread to stop it from receiving messages.
176
177**System capability**: SystemCapability.Utils.Lang
178
179**Example**
180
181```
182const workerInstance = new worker.Worker("workers/worker.js")
183workerInstance.terminate()
184```
185
186
187### onexit
188
189onexit?: (code: number) => void
190
191Defines the event handler to be called when the Worker thread exits. The handler is executed in the host thread.
192
193**System capability**: SystemCapability.Utils.Lang
194
195**Parameters**
196
197| Name| Type  | Mandatory| Description              |
198| ------ | ------ | ---- | ------------------ |
199| code   | number | No  | Code indicating the Worker thread exit state.|
200
201**Example**
202
203```
204const workerInstance = new worker.Worker("workers/worker.js")
205workerInstance.onexit = function(e) {
206    console.log("onexit")
207}
208```
209
210
211### onerror
212
213onerror?: (err: ErrorEvent) => void
214
215Defines the event handler to be called when an exception occurs during Worker execution. The event handler is executed in the host thread.
216
217**System capability**: SystemCapability.Utils.Lang
218
219**Parameters**
220
221| Name| Type                     | Mandatory| Description      |
222| ------ | ------------------------- | ---- | ---------- |
223| err    | [ErrorEvent](#errorevent) | No  | Error data.|
224
225**Example**
226
227```
228const workerInstance = new worker.Worker("workers/worker.js")
229workerInstance.onerror = function(e) {
230    console.log("onerror")
231}
232```
233
234
235### onmessage
236
237onmessage?: (event: MessageEvent) => void
238
239Defines the event handler to be called when the host thread receives a message created by itself and sent by the Worker thread through the **parentPort.postMessage**. The event handler is executed in the host thread.
240
241**System capability**: SystemCapability.Utils.Lang
242
243**Parameters**
244
245| Name| Type                         | Mandatory| Description                  |
246| ------ | ----------------------------- | ---- | ---------------------- |
247| event  | [MessageEvent](#messageevent) | No  | Message received.|
248
249**Example**
250
251```
252const workerInstance = new worker.Worker("workers/worker.js")
253workerInstance.onmessage = function(e) {
254    console.log("onerror")
255}
256```
257
258
259### onmessageerror
260
261onmessageerror?: (event: MessageEvent) => void
262
263Defines 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.
264
265**System capability**: SystemCapability.Utils.Lang
266
267**Parameters**
268
269| Name| Type                         | Mandatory| Description      |
270| ------ | ----------------------------- | ---- | ---------- |
271| event  | [MessageEvent](#messageevent) | No  | Error data.|
272
273**Example**
274
275```
276const workerInstance = new worker.Worker("workers/worker.js")
277workerInstance.onmessageerror= function(e) {
278    console.log("onmessageerror")
279}
280```
281
282
283## EventTarget
284
285
286### addEventListener
287
288addEventListener(type: string, listener: EventListener): void
289
290Adds an event listener for the Worker thread.
291
292**System capability**: SystemCapability.Utils.Lang
293
294**Parameters**
295
296| Name  | Type                           | Mandatory| Description            |
297| -------- | ------------------------------- | ---- | ---------------- |
298| type     | string                          | Yes  | Type of the event to listen for.|
299| listener | [EventListener](#eventlistener) | Yes  | Callback to invoke when an event of the specified type occurs.    |
300
301**Example**
302
303```
304const workerInstance = new worker.Worker("workers/worker.js")
305workerInstance.addEventListener("alert", (e)=>{
306    console.log("alert listener callback");
307})
308```
309
310
311### removeEventListener
312
313removeEventListener(type: string, callback?: EventListener): void
314
315Removes an event listener for the Worker thread.
316
317**System capability**: SystemCapability.Utils.Lang
318
319**Parameters**
320
321| Name  | Type                           | Mandatory| Description                  |
322| -------- | ------------------------------- | ---- | ---------------------- |
323| type     | string                          | Yes  | Type of the event for which the event listener is removed.  |
324| callback | [EventListener](#eventlistener) | No  | Callback of the event listener to remove.|
325
326**Example**
327
328```
329const workerInstance = new worker.Worker("workers/worker.js")
330workerInstance.removeEventListener("alert")
331```
332
333
334### dispatchEvent
335
336dispatchEvent(event: Event): boolean
337
338Dispatches the event defined for the Worker thread.
339
340**System capability**: SystemCapability.Utils.Lang
341
342**Parameters**
343
344| Name| Type           | Mandatory| Description            |
345| ------ | --------------- | ---- | ---------------- |
346| event  | [Event](#event) | Yes  | Event to dispatch.|
347
348**Return value**
349
350| Type   | Description                           |
351| ------- | ------------------------------- |
352| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.|
353
354**Example**
355
356```
357const workerInstance = new worker.Worker("workers/worker.js")
358workerInstance.dispatchEvent({type:"alert"})
359```
360
361
362### removeAllListener
363
364removeAllListener(): void
365
366Removes all event listeners for the Worker thread.
367
368**System capability**: SystemCapability.Utils.Lang
369
370**Example**
371
372```
373const workerInstance = new worker.Worker("workers/worker.js")
374workerInstance.removeAllListener({type:"alert"})
375```
376
377
378## DedicatedWorkerGlobalScope
379
380Implements communication between the Worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the Worker thread. The **DedicatedWorkerGlobalScope** class inherits from [WorkerGlobalScope](#workerglobalscope).
381
382
383### postMessage
384
385postMessage(message: Object, options?: PostMessageOptions): void
386
387Sends a message to the host thread from the Worker thread.
388
389**System capability**: SystemCapability.Utils.Lang
390
391**Parameters**
392
393| Name | Type                                     | Mandatory| Description                                                        |
394| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
395| message | Object                                    | Yes  | Data to be sent to the Worker thread.                                        |
396| options | [PostMessageOptions](#postmessageoptions) | No  | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.|
397
398**Example**
399
400```
401// main.js
402import worker from '@ohos.worker';
403const workerInstance = new worker.Worker("workers/worker.js")
404workerInstance.postMessage("hello world")
405workerInstance.onmessage = function(e) {
406    console.log("receive data from worker.js")
407}
408```
409
410```
411// worker.js
412import worker from '@ohos.worker';
413const parentPort = worker.parentPort;
414parentPort.onmessage = function(e){
415    parentPort.postMessage("receive data from main.js")
416}
417```
418
419
420### close
421
422close(): void
423
424Terminates the Worker thread to stop it from receiving messages.
425
426**System capability**: SystemCapability.Utils.Lang
427
428**Example**
429
430```
431// main.js
432import worker from '@ohos.worker';
433const workerInstance = new worker.Worker("workers/worker.js")
434```
435
436```
437// worker.js
438import worker from '@ohos.worker';
439const parentPort = worker.parentPort;
440parentPort.onmessage = function(e) {
441    parentPort.close()
442}
443```
444
445
446### onmessage
447
448onmessage?: (event: MessageEvent) => void
449
450Defines the event handler to be called when the Worker thread receives a message sent by the host thread through **worker.postMessage**. The event handler is executed in the Worker thread.
451
452**System capability**: SystemCapability.Utils.Lang
453
454**Parameters**
455
456| Name| Type                         | Mandatory| Description                  |
457| ------ | ----------------------------- | ---- | ---------------------- |
458| event  | [MessageEvent](#messageevent) | No  | Message received.|
459
460**Example**
461
462```
463// main.js
464import worker from '@ohos.worker';
465const workerInstance = new worker.Worker("workers/worker.js")
466workerInstance.postMessage("hello world")
467```
468
469```
470// worker.js
471import worker from '@ohos.worker';
472const parentPort = worker.parentPort;
473parentPort.onmessage = function(e) {
474    console.log("receive main.js message")
475}
476```
477
478
479### onmessageerror
480
481onmessageerror?: (event: MessageEvent) => void
482
483Defines 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.
484
485**System capability**: SystemCapability.Utils.Lang
486
487**Parameters**
488
489| Name| Type                         | Mandatory| Description      |
490| ------ | ----------------------------- | ---- | ---------- |
491| event  | [MessageEvent](#messageevent) | No  | Error data.|
492
493**Example**
494
495```
496// main.js
497import worker from '@ohos.worker';
498const workerInstance = new worker.Worker("workers/worker.js")
499```
500
501```
502// worker.js
503import worker from '@ohos.worker';
504const parentPort = worker.parentPort;
505parentPort.onmessageerror= function(e) {
506    console.log("worker.js onmessageerror")
507}
508```
509
510
511## PostMessageOptions
512
513Specifies the object whose ownership needs to be transferred during data transfer. The object must be **ArrayBuffer**.
514
515**System capability**: SystemCapability.Utils.Lang
516
517| Name    | Type| Readable| Writable| Description                             |
518| -------- | -------- | ---- | ---- | --------------------------------- |
519| transfer | Object[] | Yes  | Yes  | **ArrayBuffer** array used to transfer the ownership.|
520
521
522## Event
523
524Defines the event.
525
526**System capability**: SystemCapability.Utils.Lang
527
528| Name     | Type| Readable| Writable| Description                              |
529| --------- | -------- | ---- | ---- | ---------------------------------- |
530| type      | string   | Yes  | No  | Type of the event.                  |
531| timeStamp | number   | Yes  | No  | Timestamp (accurate to millisecond) when the event is created.|
532
533
534## EventListener
535
536Implements event listening.
537
538
539### (evt: Event): void | Promise<void>
540
541Specifies the callback to invoke.
542
543**System capability**: SystemCapability.Utils.Lang
544
545**Parameters**
546
547| Name| Type           | Mandatory| Description          |
548| ------ | --------------- | ---- | -------------- |
549| evt    | [Event](#event) | Yes  | Event class for the callback to invoke.|
550
551**Return value**
552
553| Type                                 | Description                           |
554| ------------------------------------- | ------------------------------- |
555| void \| Promise<void> | Returns no value or returns a **Promise**.|
556
557**Example**
558
559```
560const workerInstance = new worker.Worker("workers/worker.js");
561workerInstance.addEventListener("alert", (e)=>{
562    console.log("alert listener callback");
563})
564```
565
566
567## ErrorEvent
568
569Provides detailed information about the exception occurred during Worker execution. The **ErrorEvent** class inherits from [Event](#event).
570
571**System capability**: SystemCapability.Utils.Lang
572
573| Name    | Type| Readable| Writable| Description                |
574| -------- | -------- | ---- | ---- | -------------------- |
575| message  | string   | Yes  | No  | Information about the exception.|
576| filename | string   | Yes  | No  | File where the exception is located.|
577| lineno   | number   | Yes  | No  | Number of the line where the exception is located.    |
578| colno    | number   | Yes  | No  | Number of the column where the exception is located.    |
579| error    | Object   | Yes  | No  | Type of the exception.          |
580
581
582## MessageEvent
583
584Holds the data transferred between Worker threads.
585
586**System capability**: SystemCapability.Utils.Lang
587
588| Name| Type| Readable| Writable| Description              |
589| ---- | -------- | ---- | ---- | ------------------ |
590| data | T        | Yes  | No  | Data transferred between threads.|
591
592
593## WorkerGlobalScope
594
595Defines the running environment of the Worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtarget).
596
597### Attributes
598
599**System capability**: SystemCapability.Utils.Lang
600
601| Name| Type                                                    | Readable| Writable| Description                                   |
602| ---- | ------------------------------------------------------------ | ---- | ---- | --------------------------------------- |
603| name | string                                                       | Yes  | No  | **Worker** instance specified when there is a new **Worker** instance.|
604| self | [WorkerGlobalScope](#workerglobalscope) & typeof globalThis | Yes  | No  | WorkerGlobalScope.                |
605
606
607### onerror
608
609onerror?: (ev: ErrorEvent) => void
610
611Defines the event handler to be called when an exception occurs during Worker execution. The event handler is executed in the Worker thread.
612
613**System capability**: SystemCapability.Utils.Lang
614
615**Parameters**
616
617| Name| Type                     | Mandatory| Description      |
618| ------ | ------------------------- | ---- | ---------- |
619| ev     | [ErrorEvent](#errorevent) | No  | Error data.|
620
621**Example**
622
623```
624// main.js
625import worker from '@ohos.worker';
626const workerInstance = new worker.Worker("workers/worker.js")
627```
628
629```
630// worker.js
631import worker from '@ohos.worker';
632const parentPort = worker.parentPort
633parentPort.onerror = function(e){
634    console.log("worker.js onerror")
635}
636```
637