From 83225b3d136d2049ef6867f248321aedf1a29d88 Mon Sep 17 00:00:00 2001 From: buzhuyu Date: Wed, 23 Aug 2023 11:53:35 +0800 Subject: [PATCH] fixed 7eb735b from https://gitee.com/buzhuyu/docs/pulls/22769 modify taskpool and arkutils adapt to arkts Signed-off-by: buzhuyu --- .../arkts-utils/async-concurrency-overview.md | 30 +- .../cpu-intensive-task-development.md | 57 +-- .../io-intensive-task-development.md | 60 +-- .../arkts-utils/linear-container.md | 69 +-- .../multi-thread-concurrency-overview.md | 4 +- .../arkts-utils/nonlinear-container.md | 17 +- .../arkts-utils/single-io-development.md | 17 +- .../arkts-utils/sync-task-development.md | 40 +- .../arkts-utils/taskpool-vs-worker.md | 16 +- .../arkts-utils/xml-conversion.md | 42 +- .../arkts-utils/xml-generation.md | 30 +- .../arkts-utils/xml-parsing.md | 110 ++--- .../reference/apis/js-apis-taskpool.md | 465 +++++++++--------- .../reference/apis/js-apis-worker.md | 11 - 14 files changed, 465 insertions(+), 503 deletions(-) diff --git a/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md b/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md index b78e713853..c0d45f2b7f 100644 --- a/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md +++ b/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md @@ -17,16 +17,16 @@ Promise有三种状态:pending(进行中)、fulfilled(已完成)和rej ```js -const promise = new Promise((resolve, reject) => { - setTimeout(() => { - const randomNumber = Math.random(); - if (randomNumber > 0.5) { - resolve(randomNumber); - } else { - reject(new Error('Random number is too small')); - } - }, 1000); -}); +const promise: Promise = new Promise((resolve: Function, reject: Function) => { +setTimeout(() => { + const randomNumber: number = Math.random(); + if (randomNumber > 0.5) { + resolve(randomNumber); + } else { + reject(new Error('Random number is too small')); + } +}, 1000); +} ``` 上述代码中,setTimeout函数模拟了一个异步操作,并在1秒钟后随机生成一个数字。如果随机数大于0.5,则执行resolve回调函数并将随机数作为参数传递;否则执行reject回调函数并传递一个错误对象作为参数。 @@ -55,13 +55,13 @@ async函数是一个返回Promise对象的函数,用于表示一个异步操 ```js -async function myAsyncFunction() { - const result = await new Promise((resolve) => { +async function myAsyncFunction(): Promise { + const result: string = await new Promise((resolve: Function) => { setTimeout(() => { resolve('Hello, world!'); }, 3000); }); - console.info(String(result)); // 输出: Hello, world! + console.info(result); // 输出: Hello, world! } myAsyncFunction(); @@ -73,9 +73,9 @@ myAsyncFunction(); ```js -async function myAsyncFunction() { +async function myAsyncFunction(): Promise { try { - const result = await new Promise((resolve) => { + const result: string = await new Promise((resolve: Function) => { resolve('Hello, world!'); }); } catch (e) { diff --git a/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md b/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md index 19b25b18b7..f2f4b93b64 100644 --- a/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md +++ b/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md @@ -24,19 +24,19 @@ CPU密集型任务是指需要占用系统资源处理大量计算能力的任 import taskpool from '@ohos.taskpool'; @Concurrent -function imageProcessing(dataSlice: ArrayBuffer) { +function imageProcessing(dataSlice: ArrayBuffer): ArrayBuffer { // 步骤1: 具体的图像处理操作及其他耗时操作 return dataSlice; } -function histogramStatistic(pixelBuffer: ArrayBuffer) { +function histogramStatistic(pixelBuffer: ArrayBuffer): void { // 步骤2: 分成三段并发调度 - let number = pixelBuffer.byteLength / 3; - let buffer1 = pixelBuffer.slice(0, number); - let buffer2 = pixelBuffer.slice(number, number * 2); - let buffer3 = pixelBuffer.slice(number * 2); + let number: number = pixelBuffer.byteLength / 3; + let buffer1: ArrayBuffer = pixelBuffer.slice(0, number); + let buffer2: ArrayBuffer = pixelBuffer.slice(number, number * 2); + let buffer3: ArrayBuffer = pixelBuffer.slice(number * 2); - let group = new taskpool.TaskGroup(); + let group: taskpool.TaskGroup = new taskpool.TaskGroup(); group.addTask(imageProcessing, buffer1); group.addTask(imageProcessing, buffer2); group.addTask(imageProcessing, buffer3); @@ -79,30 +79,28 @@ struct Index { ![newWorker](figures/newWorker.png) 2. 在主线程中通过调用ThreadWorker的[constructor()](../reference/apis/js-apis-worker.md#constructor9)方法创建Worker对象,当前线程为宿主线程。 - + ```js import worker from '@ohos.worker'; - - const workerInstance = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + + const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); ``` 3. 在宿主线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9)方法接收Worker线程发送过来的消息,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9)方法向Worker线程发送消息。 例如向Worker线程发送训练和预测的消息,同时接收Worker线程发送回来的消息。 - + ```js // 接收Worker子线程的结果 workerInstance.onmessage = function(e) { - // data:主线程发送的信息 - let data = e.data; console.info('MyWorker.ts onmessage'); // 在Worker线程中进行耗时操作 } - + workerInstance.onerror = function (d) { // 接收Worker子线程的错误信息 } - + // 向Worker子线程发送训练消息 workerInstance.postMessage({ 'type': 0 }); // 向Worker子线程发送预测消息 @@ -110,40 +108,39 @@ struct Index { ``` 4. 在MyWorker.ts文件中绑定Worker对象,当前线程为Worker线程。 - + ```js import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; - + let workerPort: ThreadWorkerGlobalScope = worker.workerPort; ``` 5. 在Worker线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9-1)方法接收宿主线程发送的消息内容,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9-2)方法向宿主线程发送消息。 例如在Worker线程中定义预测模型及其训练过程,同时与主线程进行信息交互。 - + ```js import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; - + let workerPort: ThreadWorkerGlobalScope = worker.workerPort; - - // 定义训练模型及结果 + + // 定义训练模型及结果 let result; - + // 定义预测函数 function predict(x) { return result[x]; } - + // 定义优化器训练过程 function optimize() { result = {}; } - + // Worker线程的onmessage逻辑 - workerPort.onmessage = function (e: MessageEvents) { - let data = e.data + workerPort.onmessage = (e: MessageEvents): void => { // 根据传输的数据的type选择进行操作 - switch (data.type) { + switch (e.data.type) { case 0: // 进行训练 optimize(); @@ -152,7 +149,7 @@ struct Index { break; case 1: // 执行预测 - const output = predict(data.value); + const output = predict(e.data.value); // 发送主线程预测的结果 workerPort.postMessage({ type: 'predict', value: output }); break; @@ -166,7 +163,7 @@ struct Index { 6. 在Worker线程中完成任务之后,执行Worker线程销毁操作。销毁线程的方式主要有两种:根据需要可以在宿主线程中对Worker线程进行销毁;也可以在Worker线程中主动销毁Worker线程。 在宿主线程中通过调用[onexit()](../reference/apis/js-apis-worker.md#onexit9)方法定义Worker线程销毁后的处理逻辑。 - + ```js // Worker线程销毁后,执行onexit回调方法 workerInstance.onexit = function() { @@ -182,7 +179,7 @@ struct Index { ``` 方式二:在Worker线程中通过调用[close()](../reference/apis/js-apis-worker.md#close9)方法主动销毁Worker线程,并终止Worker接收消息。 - + ```js // 销毁线程 workerPort.close(); diff --git a/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md b/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md index 6c4410e88b..1a29cc3e00 100644 --- a/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md +++ b/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md @@ -8,43 +8,45 @@ I/O密集型任务的性能重点通常不在于CPU的处理能力,而在于I/ 1. 定义并发函数,内部密集调用I/O能力。 - + ```ts - import fs from '@ohos.file.fs'; - - // 定义并发函数,内部密集调用I/O能力 - @Concurrent - async function concurrentTest(fileList: string[]) { - // 写入文件的实现 - async function write(data, filePath) { - let file = await fs.open(filePath, fs.OpenMode.READ_WRITE); - await fs.write(file.fd, data); - fs.close(file); - } - // 循环写文件操作 - for (let i = 0; i < fileList.length; i++) { - write('Hello World!', fileList[i]).then(() => { - console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); - }).catch((err) => { - console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) - return false; - }) - } - return true; - } + import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; + + // 定义并发函数,内部密集调用I/O能力 + // 写入文件的实现 + async function write(data: string, filePath: string): Promise { + let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); + await fs.write(file.fd, data); + fs.close(file); + } + + @Concurrent + async function concurrentTest(fileList: string[]): Promise { + // 循环写文件操作 + for (let i: number = 0; i < fileList.length; i++) { + write('Hello World!', fileList[i]).then(() => { + console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); + }).catch((err: BusinessError) => { + console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) + return false; + }) + } + return true; + } ``` 2. 使用TaskPool执行包含密集I/O的并发函数:通过调用[execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute)方法执行任务,并在回调中进行调度结果处理。示例中的filePath1和filePath2的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。 - + ```ts import taskpool from '@ohos.taskpool'; - - let filePath1 = ...; // 应用文件路径 - let filePath2 = ...; - + + let filePath1: string = ...; // 应用文件路径 + let filePath2: string = ...; + // 使用TaskPool执行包含密集I/O的并发函数 // 数组较大时,I/O密集型任务任务分发也会抢占主线程,需要使用多线程能力 - taskpool.execute(concurrentTest, [filePath1, filePath2]).then((ret) => { + taskpool.execute(concurrentTest, [filePath1, filePath2]).then(() => { // 调度结果处理 console.info(`The result: ${ret}`); }) diff --git a/zh-cn/application-dev/arkts-utils/linear-container.md b/zh-cn/application-dev/arkts-utils/linear-container.md index 650feae053..088b6c7272 100644 --- a/zh-cn/application-dev/arkts-utils/linear-container.md +++ b/zh-cn/application-dev/arkts-utils/linear-container.md @@ -202,52 +202,59 @@ Stack进行增、删、改、查操作的常用API如下: // ArrayList import ArrayList from '@ohos.util.ArrayList'; // 导入ArrayList模块 -let arrayList = new ArrayList(); -arrayList.add('a'); -arrayList.add(1); // 增加元素 -console.info(`result: ${arrayList[0]}`); // 访问元素 -arrayList[0] = 'one'; // 修改元素 -console.info(`result: ${arrayList[0]}`); +let arrayList1: ArrayList = new ArrayList(); +arrayList1.add('a'); +let arrayList2: ArrayList = new ArrayList(); +arrayList2.add(1); // 增加元素 +console.info(`result: ${arrayList2[0]}`); // 访问元素 +arrayList1[0] = 'one'; // 修改元素 +console.info(`result: ${arrayList1[0]}`); // Vector import Vector from '@ohos.util.Vector'; // 导入Vector模块 -let vector = new Vector(); -vector.add('a'); +let vector1: Vector = new Vector(); +vector1.add('a'); +let vector2: Vector> = new Vector(); let b1 = [1, 2, 3]; -vector.add(b1); -vector.add(false); // 增加元素 -console.info(`result: ${vector[0]}`); // 访问元素 -console.info(`result: ${vector.getFirstElement()}`); // 访问元素 +vector2.add(b1); +let vector3: Vector = new Vector(); +vector3.add(false); // 增加元素 +console.info(`result: ${vector1[0]}`); // 访问元素 +console.info(`result: ${vector2.getFirstElement()}`); // 访问元素 // Deque import Deque from '@ohos.util.Deque'; // 导入Deque模块 -let deque = new Deque; -deque.insertFront('a'); -deque.insertFront(1); // 增加元素 -console.info(`result: ${deque[0]}`); // 访问元素 -deque[0] = 'one'; // 修改元素 -console.info(`result: ${deque[0]}`); +let deque1: Deque = new Deque; +deque1.insertFront('a'); +let deque2: Deque = new Deque; +deque2.insertFront(1); // 增加元素 +console.info(`result: ${deque1[0]}`); // 访问元素 +deque1[0] = 'one'; // 修改元素 +console.info(`result: ${deque2[0]}`); // Stack -import Stack from '@ohos.util.Stack'; // 导入Stack模块 +import Stack from '@ohos.util.Stack'; // 导入Stack模块 -let stack = new Stack(); -stack.push('a'); -stack.push(1); // 增加元素 -console.info(`result: ${stack[0]}`); // 访问元素 -stack.pop(); // 弹出元素 -console.info(`result: ${stack.length}`); +let stack1: Stack = new Stack(); +stack1.push('a'); +let stack2: Stack = new Stack(); +stack2.push(1); // 增加元素 +console.info(`result: ${stack1[0]}`); // 访问元素 +stack2.pop(); // 弹出元素 +console.info(`result: ${stack2.length}`); // List import List from '@ohos.util.List'; // 导入List模块 -let list = new List; -list.add('a'); -list.add(1); +let list1: List = new List; +list1.add('a'); +let list2: List = new List; +list2.add(1); +let list3: List> = new List; let b2 = [1, 2, 3]; -list.add(b2); // 增加元素 -console.info(`result: ${list[0]}`); // 访问元素 -console.info(`result: ${list.get(0)}`); // 访问元素 +list3.add(b2); // 增加元素 +console.info(`result: ${list1[0]}`); // 访问元素 +console.info(`result: ${list3.get(0)}`); // 访问元素 ``` diff --git a/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md b/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md index cc0cee7c6f..31271ee693 100644 --- a/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md +++ b/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md @@ -29,7 +29,7 @@ Actor并发模型作为基于消息通信并发模型的典型代表,不需要 ```js // 定义可转移对象 -let buffer = new ArrayBuffer(100); +let buffer: ArrayBuffer = new ArrayBuffer(100); ``` @@ -44,7 +44,7 @@ SharedArrayBuffer对象存储的数据在同时被修改时,需要通过原子 ```js // 定义可共享对象,可以使用Atomics进行操作 -let sharedBuffer = new SharedArrayBuffer(1024); +let sharedBuffer: SharedArrayBuffer = new SharedArrayBuffer(1024); ``` ### Native绑定对象 diff --git a/zh-cn/application-dev/arkts-utils/nonlinear-container.md b/zh-cn/application-dev/arkts-utils/nonlinear-container.md index 39cd522af9..0b35b767bf 100644 --- a/zh-cn/application-dev/arkts-utils/nonlinear-container.md +++ b/zh-cn/application-dev/arkts-utils/nonlinear-container.md @@ -216,16 +216,17 @@ PlainArray进行增、删、改、查操作的常用API如下: // HashMap import HashMap from '@ohos.util.HashMap'; // 导入HashMap模块 -let hashMap = new HashMap(); -hashMap.set('a', 123); -hashMap.set(4, 123); // 增加元素 -console.info(`result: ${hashMap.hasKey(4)}`); // 判断是否含有某元素 -console.info(`result: ${hashMap.get('a')}`); // 访问元素 +let hashMap1: HashMap = new HashMap(); +hashMap1.set('a', 123); +let hashMap2: HashMap = new HashMap(); +hashMap2.set(4, 123); // 增加元素 +console.info(`result: ${hashMap2.hasKey(4)}`); // 判断是否含有某元素 +console.info(`result: ${hashMap1.get('a')}`); // 访问元素 // TreeMap import TreeMap from '@ohos.util.TreeMap'; // 导入TreeMap模块 -let treeMap = new TreeMap(); +let treeMap: TreeMap = new TreeMap(); treeMap.set('a', 123); treeMap.set('6', 356); // 增加元素 console.info(`result: ${treeMap.get('a')}`); // 访问元素 @@ -235,7 +236,7 @@ console.info(`result: ${treeMap.getLastKey()}`); // 访问尾元素 // LightWeightMap import LightWeightMap from '@ohos.util.LightWeightMap'; // 导入LightWeightMap模块 -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set('x', 123); lightWeightMap.set('8', 356); // 增加元素 console.info(`result: ${lightWeightMap.get('a')}`); // 访问元素 @@ -245,7 +246,7 @@ console.info(`result: ${lightWeightMap.getIndexOfKey('8')}`); // 访问元素 // PlainArray import PlainArray from '@ohos.util.PlainArray' // 导入PlainArray模块 -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, 'sdd'); plainArray.add(2, 'sff'); // 增加元素 console.info(`result: ${plainArray.get(1)}`); // 访问元素 diff --git a/zh-cn/application-dev/arkts-utils/single-io-development.md b/zh-cn/application-dev/arkts-utils/single-io-development.md index 432f674d04..6b551373ea 100644 --- a/zh-cn/application-dev/arkts-utils/single-io-development.md +++ b/zh-cn/application-dev/arkts-utils/single-io-development.md @@ -5,24 +5,25 @@ Promise和async/await提供异步并发能力,适用于单次I/O任务的场 1. 实现单次I/O任务逻辑。 - + ```js import fs from '@ohos.file.fs'; - - async function write(data: string, filePath: string) { - let file = await fs.open(filePath, fs.OpenMode.READ_WRITE); - fs.write(file.fd, data).then((writeLen) => { + import { BusinessError } from '@ohos.base'; + + async function write(data: string, filePath: string): Promise { + let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); + fs.write(file.fd, data).then((writeLen: number) => { fs.close(file); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`); }) } ``` 2. 采用异步能力调用单次I/O任务。示例中的filePath的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。 - + ```js - let filePath = ...; // 应用文件路径 + let filePath: string = ...; // 应用文件路径 write('Hello World!', filePath).then(() => { console.info('Succeeded in writing data.'); }) diff --git a/zh-cn/application-dev/arkts-utils/sync-task-development.md b/zh-cn/application-dev/arkts-utils/sync-task-development.md index 8fb185d44a..6fbb549708 100644 --- a/zh-cn/application-dev/arkts-utils/sync-task-development.md +++ b/zh-cn/application-dev/arkts-utils/sync-task-development.md @@ -25,18 +25,16 @@ ```ts // Handle.ts 代码 export default class Handle { - static getInstance() { + static getInstance(): void { // 返回单例对象 } - static syncGet() { + static syncGet(): void { // 同步Get方法 - return; } - static syncSet(num: number) { + static syncSet(num: number): void { // 同步Set方法 - return; } } ``` @@ -51,7 +49,7 @@ import Handle from './Handle'; // 返回静态句柄 // 步骤1: 定义并发函数,内部调用同步方法 @Concurrent -function func(num: number) { +function func(num: number): boolean { // 调用静态类对象中实现的同步等待调用 Handle.syncSet(num); // 或者调用单例对象中实现的同步等待调用 @@ -60,13 +58,11 @@ function func(num: number) { } // 步骤2: 创建任务并执行 -async function asyncGet() { +async function asyncGet(): Promise { // 创建task并传入函数func - let task = new taskpool.Task(func, 1); - // 执行task任务,获取结果res - let res = await taskpool.execute(task); - // 对同步逻辑后的结果进行操作 - console.info(String(res)); + let task: taskpool.Task = new taskpool.Task(func, 1); + // 执行task任务并对同步逻辑后的结果进行操作 + console.info(String(await taskpool.execute(task))); } @Entry @@ -98,15 +94,15 @@ struct Index { 当一系列同步任务需要使用同一个句柄调度,或者需要依赖某个类对象调度,无法在不同任务池之间共享时,需要使用Worker。 1. 在主线程中创建Worker对象,同时接收Worker线程发送回来的消息。 - + ```js import worker from '@ohos.worker'; - + @Entry @Component struct Index { @State message: string = 'Hello World'; - + build() { Row() { Column() { @@ -114,7 +110,7 @@ struct Index { .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { - let w = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); w.onmessage = function (d) { // 接收Worker子线程的结果 } @@ -137,28 +133,28 @@ struct Index { ``` 2. 在Worker线程中绑定Worker对象,同时处理同步任务逻辑。 - + ```js // handle.ts代码 export default class Handle { syncGet() { return; } - + syncSet(num: number) { return; } } - + // Worker.ts代码 import worker, { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker'; import Handle from './handle.ts' // 返回句柄 - + var workerPort : ThreadWorkerGlobalScope = worker.workerPort; - + // 无法传输的句柄,所有操作依赖此句柄 var handler = new Handle() - + // Worker线程的onmessage逻辑 workerPort.onmessage = function(e : MessageEvents) { switch (e.data.type) { diff --git a/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md b/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md index d77ce59b98..4cf19aae5a 100644 --- a/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md +++ b/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md @@ -102,9 +102,9 @@ TaskPool支持开发者在主线程封装任务抛给任务队列,系统选择 ```js // API 9及之后版本使用: -const worker1 = new worker.ThreadWorker(scriptURL); +const worker1: worker.ThreadWorker = new worker.ThreadWorker(scriptURL); // API 8及之前版本使用: -const worker1 = new worker.Worker(scriptURL); +const worker1: worker.ThreadWorker = new worker.Worker(scriptURL); ``` 构造函数需要传入Worker的路径(scriptURL),Worker文件存放位置默认路径为Worker文件所在目录与pages目录属于同级。 @@ -119,15 +119,15 @@ const worker1 = new worker.Worker(scriptURL); ```js // 写法一 // Stage模型-目录同级(entry模块下,workers目录与pages目录同级) -const worker1 = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"}); +const worker1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"}); // Stage模型-目录不同级(entry模块下,workers目录是pages目录的子目录) -const worker2 = new worker.ThreadWorker('entry/ets/pages/workers/MyWorker.ts'); +const worker2: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/pages/workers/MyWorker.ts'); // 写法二 // Stage模型-目录同级(entry模块下,workers目录与pages目录同级),假设bundlename是com.example.workerdemo -const worker3 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker'); +const worker3: worker.ThreadWorker = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker'); // Stage模型-目录不同级(entry模块下,workers目录是pages目录的子目录),假设bundlename是com.example.workerdemo -const worker4 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker'); +const worker4: worker.ThreadWorker = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker'); ``` @@ -151,9 +151,9 @@ const worker4 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/et ```js // FA模型-目录同级(entry模块下,workers目录与pages目录同级) -const worker1 = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'}); +const worker1: worker.ThreadWorker = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'}); // FA模型-目录不同级(entry模块下,workers目录与pages目录的父目录同级) -const worker2 = new worker.ThreadWorker('../workers/worker.js'); +const worker2: worker.ThreadWorker = new worker.ThreadWorker('../workers/worker.js'); ``` diff --git a/zh-cn/application-dev/arkts-utils/xml-conversion.md b/zh-cn/application-dev/arkts-utils/xml-conversion.md index a47c733357..100d5112be 100644 --- a/zh-cn/application-dev/arkts-utils/xml-conversion.md +++ b/zh-cn/application-dev/arkts-utils/xml-conversion.md @@ -17,22 +17,22 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 此处以XML转为JavaScript对象后获取其标签值为例,说明转换效果。 1. 引入模块。 - + ```js import convertxml from '@ohos.convertxml'; ``` 2. 输入待转换的XML,设置转换选项。 - + ```js - let xml = - '' + - '' + - ' Happy' + - ' Work' + - ' Play' + - ''; - let options = { + let xml: string = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; + let options: convertxml.ConvertOptions = { // trim: false 转换后是否删除文本前后的空格,否 // declarationKey: "_declaration" 转换后文件声明使用_declaration来标识 // instructionKey: "_instruction" 转换后指令使用_instruction标识 @@ -51,7 +51,7 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 attributesKey: "_attributes", textKey: "_text", cdataKey: "_cdata", - docTypeKey: "_doctype", + doctypeKey: "_doctype", commentKey: "_comment", parentKey: "_parent", typeKey: "_type", @@ -61,24 +61,17 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 ``` 3. 调用转换函数,打印结果。 - + ```js - let conv = new convertxml.ConvertXML(); - let result = conv.convertToJSObject(xml, options); - let strRes = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出 + let conv: convertxml.ConvertXML = new convertxml.ConvertXML(); + let result: object = conv.convertToJSObject(xml, options); + let strRes: string = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出 console.info(strRes); - // 也可以直接处理转换后的JS对象,获取标签值 - let title = result['_elements'][0]['_elements'][0]['_elements'][0]['_text']; // 解析标签对应的值 - let todo = result['_elements'][0]['_elements'][1]['_elements'][0]['_text']; // 解析<todo>标签对应的值 - let todo2 = result['_elements'][0]['_elements'][2]['_elements'][0]['_text']; // 解析<todo>标签对应的值 - console.info(title); // Happy - console.info(todo); // Work - console.info(todo2); // Play ``` 输出结果如下所示: - + ```js strRes: {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note", @@ -86,7 +79,4 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 "_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo", "_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo", "_elements":[{"_type":"text","_text":"Play"}]}]}]} - title:Happy - todo:Work - todo2:Play ``` diff --git a/zh-cn/application-dev/arkts-utils/xml-generation.md b/zh-cn/application-dev/arkts-utils/xml-generation.md index 2e3013f0fc..60edf5c6d3 100644 --- a/zh-cn/application-dev/arkts-utils/xml-generation.md +++ b/zh-cn/application-dev/arkts-utils/xml-generation.md @@ -23,27 +23,27 @@ XML模块提供XmlSerializer类来生成XML文件,输入为固定长度的Arra XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md)的详细描述,按需求调用对应函数可以生成一份完整的XML文件。 1. 引入模块。 - + ```js - import xml from '@ohos.xml'; + import xml from '@ohos.xml'; import util from '@ohos.util'; ``` 2. 创建缓冲区,构造XmlSerializer对象(可以基于Arraybuffer构造XmlSerializer对象, 也可以基于DataView构造XmlSerializer对象)。 - + ```js // 1.基于Arraybuffer构造XmlSerializer对象 - let arrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 - let thatSer = new xml.XmlSerializer(arrayBuffer); // 基于Arraybuffer构造XmlSerializer对象 - + let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 + let thatSer: xml.XmlSerializer = new xml.XmlSerializer(arrayBuffer); // 基于Arraybuffer构造XmlSerializer对象 + // 2.基于DataView构造XmlSerializer对象 - let arrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 - let dataView = new DataView(arrayBuffer); // 使用DataView对象操作ArrayBuffer对象 - let thatSer = new xml.XmlSerializer(dataView); // 基于DataView构造XmlSerializer对象 + let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 + let dataView: DataView = new DataView(arrayBuffer); // 使用DataView对象操作ArrayBuffer对象 + let thatSer: xml.XmlSerializer = new xml.XmlSerializer(dataView); // 基于DataView构造XmlSerializer对象 ``` 3. 调用XML元素生成函数。 - + ```js thatSer.setDeclaration(); // 写入xml的声明 thatSer.startElement('bookstore'); // 写入元素开始标记 @@ -64,17 +64,17 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md) ``` 4. 使用Uint8Array操作Arraybuffer,调用TextDecoder对Uint8Array解码后输出。 - + ```js - let view = new Uint8Array(arrayBuffer); // 使用Uint8Array读取arrayBuffer的数据 - let textDecoder = util.TextDecoder.create(); // 调用util模块的TextDecoder类 - let res = textDecoder.decodeWithStream(view); // 对view解码 + let view: Uint8Array = new Uint8Array(arrayBuffer); // 使用Uint8Array读取arrayBuffer的数据 + let textDecoder: util.TextDecoder = util.TextDecoder.create(); // 调用util模块的TextDecoder类 + let res: string = textDecoder.decodeWithStream(view); // 对view解码 console.info(res); ``` 输出结果如下: - + ```js <?xml version=\"1.0\" encoding=\"utf-8\"?><bookstore>\r\n <book category=\"COOKING\">\r\n <title lang=\"en\">Everyday\r\n Giada\r\n 2005\r\n \r\n ``` diff --git a/zh-cn/application-dev/arkts-utils/xml-parsing.md b/zh-cn/application-dev/arkts-utils/xml-parsing.md index e53a2d830d..5df577246c 100644 --- a/zh-cn/application-dev/arkts-utils/xml-parsing.md +++ b/zh-cn/application-dev/arkts-utils/xml-parsing.md @@ -28,7 +28,7 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ## 解析XML标签和标签值 1. 引入模块。 - + ```js import xml from '@ohos.xml'; import util from '@ohos.util'; // 需要使用util模块函数对文件编码 @@ -37,29 +37,29 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A 2. 对XML文件编码后调用XmlPullParser。 可以基于ArrayBuffer构造XmlPullParser对象, 也可以基于DataView构造XmlPullParser对象。 - + ```js - let strXml = - '' + - '' + - 'Play' + - 'Work' + - ''; - let textEncoder = new util.TextEncoder(); - let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - // 1.基于ArrayBuffer构造XmlPullParser对象 - let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); - - // 2.基于DataView构造XmlPullParser对象 - let dataView = new DataView(arrBuffer.buffer); - let that = new xml.XmlPullParser(dataView, 'UTF-8'); + let strXml: string = + '' + + '' + + 'Play' + + 'Work' + + ''; + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + // 1.基于ArrayBuffer构造XmlPullParser对象 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + + // 2.基于DataView构造XmlPullParser对象 + let dataView: DataView = new DataView(arrBuffer.buffer); + let that: xml.XmlPullParser = new xml.XmlPullParser(dataView, 'UTF-8'); ``` 3. 自定义回调函数,本例直接打印出标签及标签值。 - + ```js - let str = ''; - function func(name, value){ + let str: string = ''; + function func(name: string, value: string): boolean { str = name + value; console.info(str); return true; //true:继续解析 false:停止解析 @@ -67,15 +67,15 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ``` 4. 设置解析选项,调用parse函数。 - + ```js - let options = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func}; + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func}; that.parse(options); ``` 输出结果如下所示: - + ```js note title @@ -91,48 +91,48 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ## 解析XML属性和属性值 1. 引入模块。 - + ```js import xml from '@ohos.xml'; import util from '@ohos.util'; // 需要使用util模块函数对文件编码 ``` 2. 对XML文件编码后调用XmlPullParser。 - + ```js - let strXml = + let strXml: string = '' + '' + ' Play' + ' Happy' + ' Work' + ''; - let textEncoder = new util.TextEncoder(); - let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); ``` 3. 自定义回调函数,本例直接打印出属性及属性值。 - + ```js - let str = ''; - function func(name, value){ + let str: string = ''; + function func(name: string, value: string): boolean { str += name + ' ' + value + ' '; return true; // true:继续解析 false:停止解析 } ``` 4. 设置解析选项,调用parse函数。 - + ```js - let options = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; that.parse(options); console.info(str); // 一次打印出所有的属性及其值 ``` 输出结果如下所示: - + ```js importance high logged true // note节点的属性及属性值 ``` @@ -141,30 +141,30 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ## 解析XML事件类型和元素深度 1. 引入模块。 - + ```js import xml from '@ohos.xml'; import util from '@ohos.util'; // 需要使用util模块函数对文件编码 ``` 2. 对XML文件编码后调用XmlPullParser。 - + ```js - let strXml = + let strXml: string = '' + '' + 'Play' + ''; - let textEncoder = new util.TextEncoder(); - let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); ``` 3. 自定义回调函数,本例直接打印元素事件类型及元素深度。 - + ```js - let str = ''; - function func(name, value){ + let str: string = ''; + function func(name: string, value: xml.ParseInfo): boolean { str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度 console.info(str) return true; //true:继续解析 false:停止解析 @@ -172,15 +172,15 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ``` 4. 设置解析选项,调用parse函数。 - + ```js - let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; that.parse(options); ``` 输出结果如下所示: - + ```js 0 0 // 0: 对应事件类型START_DOCUMENT值为0 0:起始深度为0 2 1 // 2: 对应事件类型START_TAG值为2 1:深度为1 @@ -201,36 +201,36 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A import xml from '@ohos.xml'; import util from '@ohos.util'; -let strXml = +let strXml: string = '' + '' + 'Everyday' + 'Giada' + ''; -let textEncoder = new util.TextEncoder(); -let arrBuffer = textEncoder.encodeInto(strXml); -let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); -let str = ''; +let textEncoder: util.TextEncoder = new util.TextEncoder(); +let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); +let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); +let str: string = ''; -function tagFunc(name, value) { +function tagFunc(name: string, value: string): boolean { str = name + value; console.info('tag-' + str); return true; } -function attFunc(name, value) { +function attFunc(name: string, value: string): boolean { str = name + ' ' + value; console.info('attri-' + str); return true; } -function tokenFunc(name, value) { +function tokenFunc(name: string, value: xml.ParseInfo): boolean { str = name + ' ' + value.getDepth(); console.info('token-' + str); return true; } -let options = { +let options: xml.ParseOptions = { supportDocType: true, ignoreNameSpace: true, tagValueCallbackFunction: tagFunc, diff --git a/zh-cn/application-dev/reference/apis/js-apis-taskpool.md b/zh-cn/application-dev/reference/apis/js-apis-taskpool.md index 02fc84bc6e..ece8779b4b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-taskpool.md +++ b/zh-cn/application-dev/reference/apis/js-apis-taskpool.md @@ -51,12 +51,12 @@ execute(func: Function, ...args: unknown[]): Promise\ ```ts @Concurrent -function printArgs(args) { +function printArgs(args: number): number { console.log("printArgs: " + args); return args; } -taskpool.execute(printArgs, 100).then((value) => { // 100: test number +taskpool.execute(printArgs, 100).then((value: number) => { // 100: test number console.log("taskpool result: " + value); }); ``` @@ -96,13 +96,13 @@ execute(task: Task, priority?: Priority): Promise\ ```ts @Concurrent -function printArgs(args) { +function printArgs(args: number): number { console.log("printArgs: " + args); return args; } -let task = new taskpool.Task(printArgs, 100); // 100: test number -taskpool.execute(task).then((value) => { +let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number +taskpool.execute(task).then((value: number) => { console.log("taskpool result: " + value); }); ``` @@ -140,32 +140,28 @@ execute(group: TaskGroup, priority?: Priority): Promise ```ts @Concurrent -function printArgs(args) { +function printArgs(args: number): number { console.log("printArgs: " + args); return args; } -let taskGroup1 = new taskpool.TaskGroup(); +let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup1.addTask(printArgs, 10); // 10: test number taskGroup1.addTask(printArgs, 20); // 20: test number taskGroup1.addTask(printArgs, 30); // 30: test number -let taskGroup2 = new taskpool.TaskGroup(); -let task1 = new taskpool.Task(printArgs, 100); // 100: test number -let task2 = new taskpool.Task(printArgs, 200); // 200: test number -let task3 = new taskpool.Task(printArgs, 300); // 300: test number +let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup(); +let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number +let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number +let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number taskGroup2.addTask(task1); taskGroup2.addTask(task2); taskGroup2.addTask(task3); -taskpool.execute(taskGroup1).then((res) => { +taskpool.execute(taskGroup1).then((res: Array) => { console.info("taskpool execute res is:" + res); -}).catch((e) => { - console.error("taskpool execute error is:" + e); }); -taskpool.execute(taskGroup2).then((res) => { +taskpool.execute(taskGroup2).then((res: Array) => { console.info("taskpool execute res is:" + res); -}).catch((e) => { - console.error("taskpool execute error is:" + e); }); ``` @@ -198,41 +194,39 @@ cancel(task: Task): void ```ts @Concurrent -function inspectStatus(arg) { - // 第一时间检查取消并回复 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled before 2s sleep."); - return arg + 2; - } - // 2s sleep - let t = Date.now(); - while (Date.now() - t < 2000) { - continue; - } - // 第二次检查取消并作出响应 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled after 2s sleep."); - return arg + 3; - } - return arg + 1; +function inspectStatus(arg: number): number { + // 第一时间检查取消并回复 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // 2s sleep + let t: number = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // 第二次检查取消并作出响应 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } + return arg + 1; } -let task1 = new taskpool.Task(inspectStatus, 100); // 100: test number -let task2 = new taskpool.Task(inspectStatus, 200); // 200: test number -let task3 = new taskpool.Task(inspectStatus, 300); // 300: test number -let task4 = new taskpool.Task(inspectStatus, 400); // 400: test number -let task5 = new taskpool.Task(inspectStatus, 500); // 500: test number -let task6 = new taskpool.Task(inspectStatus, 600); // 600: test number -taskpool.execute(task1).then((res)=>{ +let task1: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number +let task2: taskpool.Task = new taskpool.Task(inspectStatus, 200); // 200: test number +let task3: taskpool.Task = new taskpool.Task(inspectStatus, 300); // 300: test number +let task4: taskpool.Task = new taskpool.Task(inspectStatus, 400); // 400: test number +let task5: taskpool.Task = new taskpool.Task(inspectStatus, 500); // 500: test number +let task6: taskpool.Task = new taskpool.Task(inspectStatus, 600); // 600: test number +taskpool.execute(task1).then((res: number)=>{ console.log("taskpool test result: " + res); -}).catch((err) => { - console.log("taskpool test occur error: " + err); }); -let res2 = taskpool.execute(task2); -let res3 = taskpool.execute(task3); -let res4 = taskpool.execute(task4); -let res5 = taskpool.execute(task5); -let res6 = taskpool.execute(task6); +taskpool.execute(task2); +taskpool.execute(task3); +taskpool.execute(task4); +taskpool.execute(task5); +taskpool.execute(task6); // 1s后取消task setTimeout(()=>{ taskpool.cancel(task1);}, 1000); @@ -264,23 +258,23 @@ cancel(group: TaskGroup): void ```ts @Concurrent -function printArgs(args) { - let t = Date.now(); - while (Date.now() - t < 2000) { - continue; - } - console.log("printArgs: " + args); - return args; +function printArgs(args: number): number { + let t: number = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + console.log("printArgs: " + args); + return args; } -let taskGroup1 = new taskpool.TaskGroup(); +let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup1.addTask(printArgs, 10); // 10: test number -let taskGroup2 = new taskpool.TaskGroup(); +let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup2.addTask(printArgs, 100); // 100: test number -taskpool.execute(taskGroup1).then((res)=>{ +taskpool.execute(taskGroup1).then((res: Array)=>{ console.info("taskGroup1 res is:" + res) }); -taskpool.execute(taskGroup2).then((res)=>{ +taskpool.execute(taskGroup2).then((res: Array)=>{ console.info("taskGroup2 res is:" + res) }); setTimeout(()=>{ @@ -310,7 +304,7 @@ getTaskPoolInfo(): TaskPoolInfo **示例:** ```ts -let taskpoolInfo = taskpool.getTaskPoolInfo(); +let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo(); ``` ## Priority @@ -329,35 +323,29 @@ let taskpoolInfo = taskpool.getTaskPoolInfo(); ```ts @Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; +function printArgs(args: number): number { + console.log("printArgs: " + args); + return args; } -let task = new taskpool.Task(printArgs, 100); // 100: test number +let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number let highCount = 0; let mediumCount = 0; let lowCount = 0; let allCount = 100; -for (let i = 0; i < allCount; i++) { +for (let i: number = 0; i < allCount; i++) { taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => { lowCount++; console.log("taskpool lowCount is :" + lowCount); - }).catch((e) => { - console.error("low task error: " + e); - }) + }); taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => { mediumCount++; console.log("taskpool mediumCount is :" + mediumCount); - }).catch((e) => { - console.error("medium task error: " + e); - }) + }); taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => { highCount++; console.log("taskpool highCount is :" + highCount); - }).catch((e) => { - console.error("high task error: " + e); - }) + }); } ``` @@ -392,12 +380,12 @@ Task的构造函数。 ```ts @Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; +function printArgs(args: number): number { + console.log("printArgs: " + args); + return args; } -let task = new taskpool.Task(printArgs, "this is my first Task"); +let task: taskpool.Task = new taskpool.Task(printArgs, "this is my first Task"); ``` ### isCanceled10+ @@ -418,7 +406,7 @@ static isCanceled(): boolean ```ts @Concurrent -function inspectStatus(arg) { +function inspectStatus(arg: number): number { // do something if (taskpool.Task.isCanceled()) { console.log("task has been canceled."); @@ -437,29 +425,29 @@ function inspectStatus(arg) { ```ts @Concurrent -function inspectStatus(arg) { - // 第一时间检查取消并回复 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled before 2s sleep."); - return arg + 2; - } - // 延时2s - let t = Date.now(); - while (Date.now() - t < 2000) { - continue; - } - // 第二次检查取消并作出响应 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled after 2s sleep."); - return arg + 3; - } +function inspectStatus(arg: number): number { + // 第一时间检查取消并回复 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // 延时2s + let t: number = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // 第二次检查取消并作出响应 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } return arg + 1; } -let task = new taskpool.Task(inspectStatus, 100); // 100: test number -taskpool.execute(task).then((res)=>{ +let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number +taskpool.execute(task).then((res: number)=>{ console.log("taskpool test result: " + res); -}).catch((err) => { +}).catch((err: string) => { console.log("taskpool test occur error: " + err); }); // 不调用cancel,isCanceled()默认返回false,task执行的结果为101 @@ -485,24 +473,24 @@ setTransferList(transfer?: ArrayBuffer[]): void **示例:** ```ts -let buffer = new ArrayBuffer(8); -let view = new Uint8Array(buffer); -let buffer1 = new ArrayBuffer(16); -let view1 = new Uint8Array(buffer1); +let buffer: ArrayBuffer = new ArrayBuffer(8); +let view: Uint8Array = new Uint8Array(buffer); +let buffer1: ArrayBuffer = new ArrayBuffer(16); +let view1: Uint8Array = new Uint8Array(buffer1); console.info("testTransfer view byteLength: " + view.byteLength); console.info("testTransfer view1 byteLength: " + view1.byteLength); @Concurrent -function testTransfer(arg1, arg2) { +function testTransfer(arg1: ArrayBuffer, arg2: ArrayBuffer): number { console.info("testTransfer arg1 byteLength: " + arg1.byteLength); console.info("testTransfer arg2 byteLength: " + arg2.byteLength); return 100; } -let task = new taskpool.Task(testTransfer, view, view1); +let task: taskpool.Task = new taskpool.Task(testTransfer, view, view1); task.setTransferList([view.buffer, view1.buffer]); -taskpool.execute(task).then((res)=>{ +taskpool.execute(task).then((res: number)=>{ console.info("test result: " + res); -}).catch((e)=>{ +}).catch((e: string)=>{ console.error("test catch: " + e); }) console.info("testTransfer view byteLength: " + view.byteLength); @@ -563,12 +551,12 @@ addTask(func: Function, ...args: unknown[]): void ```ts @Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; +function printArgs(args: number): number { + console.log("printArgs: " + args); + return args; } -let taskGroup = new taskpool.TaskGroup(); +let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup.addTask(printArgs, 100); // 100: test number ``` @@ -598,13 +586,13 @@ addTask(task: Task): void ```ts @Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; +function printArgs(args: number): number { + console.log("printArgs: " + args); + return args; } -let taskGroup = new taskpool.TaskGroup(); -let task = new taskpool.Task(printArgs, 200); // 200: test number +let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(); +let task: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number taskGroup.addTask(task); ``` @@ -675,12 +663,6 @@ taskGroup.addTask(task); ### 序列化支持类型 序列化支持类型包括:All Primitive Type(不包括symbol)、Date、String、RegExp、Array、Map、Set、Object、ArrayBuffer、TypedArray。 -### 注意事项 -- 仅支持在Stage模型且module的compileMode为esmodule的project中使用taskpool api。确认module的compileMode方法:查看当前module的build-profile.json5,在buildOption中补充"compileMode": "esmodule"。 -- taskpool任务只支持引用入参传递或者import的变量,不支持使用闭包变量,使用装饰器@Concurrent进行拦截。 -- taskpool任务只支持普通函数或者async函数,不支持类成员函数或者匿名函数,使用装饰器@Concurrent进行拦截。 -- 装饰器@Concurrent仅支持在ets文件使用。 - ### 简单使用 **示例一** @@ -688,22 +670,17 @@ taskGroup.addTask(task); ```ts // 支持普通函数、引用入参传递 @Concurrent -function printArgs(args) { - console.log("func: " + args); - return args; +function printArgs(args: number): number { + console.log("func: " + args); + return args; } - -async function taskpoolExecute() { +async function taskpoolExecute(): Promise { // taskpool.execute(task) - let task = new taskpool.Task(printArgs, "create task, then execute"); - let val1 = await taskpool.execute(task); - console.log("taskpool.execute(task) result: " + val1); - + let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute"); + console.log("taskpool.execute(task) result: " + await taskpool.execute(task)); // taskpool.execute(function) - let val2 = await taskpool.execute(printArgs, "execute task by func"); - console.log("taskpool.execute(function) result: " + val2); + console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func")); } - taskpoolExecute(); ``` @@ -711,7 +688,7 @@ taskpoolExecute(); ```ts // b.ets -export let c = 2000; +export let c: number = 2000; ``` ```ts // 引用import变量 @@ -719,7 +696,7 @@ export let c = 2000; import { c } from "./b"; @Concurrent -function printArgs(a) { +function printArgs(a: number): number { console.log(a); console.log(c); return a; @@ -727,13 +704,11 @@ function printArgs(a) { async function taskpoolExecute() { // taskpool.execute(task) - let task = new taskpool.Task(printArgs, "create task, then execute"); - let val1 = await taskpool.execute(task); - console.log("taskpool.execute(task) result: " + val1); + let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute"); + console.log("taskpool.execute(task) result: " + await taskpool.execute(task)); // taskpool.execute(function) - let val2 = await taskpool.execute(printArgs, "execute task by func"); - console.log("taskpool.execute(function) result: " + val2); + console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func")); } taskpoolExecute(); @@ -752,8 +727,10 @@ async function delayExcute() { } async function taskpoolExecute() { - taskpool.execute(delayExcute).then((result) => { - console.log("TaskPoolTest task result: " + result); + taskpool.execute(delayExcute).then((result: string) => { + console.log("taskPoolTest task result: " + result); + }).catch((err: string) => { + console.log("taskpool test occur error: " + err); }); } @@ -765,24 +742,25 @@ taskpoolExecute(); ```ts // c.ets @Concurrent -function strSort(inPutArr) { +function strSort(inPutArr: Array): Array { let newArr = inPutArr.sort(); return newArr; } export async function func1() { - console.log("taskpoolTest start"); - let strArray = ['c test string', 'b test string', 'a test string']; - let task = new taskpool.Task(strSort, strArray); - let result = await taskpool.execute(task); - console.log("func1 result:" + result); + console.log("taskpoolTest start"); + let strArray: Array = ['c test string', 'b test string', 'a test string']; + let task: taskpool.Task = new taskpool.Task(strSort, strArray); + console.log("func1 result:" + await taskpool.execute(task)); } export async function func2() { - console.log("taskpoolTest2 start"); - let strArray = ['c test string', 'b test string', 'a test string']; - taskpool.execute(strSort, strArray).then((result) => { - console.log("func2 result: " + result); - }); + console.log("taskpoolTest2 start"); + let strArray: Array = ['c test string', 'b test string', 'a test string']; + taskpool.execute(strSort, strArray).then((result: Array) => { + console.log("func2 result: " + result); + }).catch((err: string) => { + console.log("taskpool test occur error: " + err); + }); } ``` @@ -799,35 +777,35 @@ func2(); ```ts // 任务取消成功 @Concurrent -function inspectStatus(arg) { - // 第一时间检查取消并回复 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled before 2s sleep."); - return arg + 2; - } - // 2s sleep - let t = Date.now(); - while (Date.now() - t < 2000) { - continue; - } - // 第二次检查取消并作出响应 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled after 2s sleep."); - return arg + 3; - } - return arg + 1; +function inspectStatus(arg: number): number { + // 第一时间检查取消并回复 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // 2s sleep + let t: number = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // 第二次检查取消并作出响应 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } + return arg + 1; } -async function taskpoolCancel() { - let task = new taskpool.Task(inspectStatus, 100); // 100: test number - taskpool.execute(task).then((res)=>{ - console.log("taskpool test result: " + res); - }).catch((err) => { - console.log("taskpool test occur error: " + err); - }); - // 1s后取消task - setTimeout(()=>{ - taskpool.cancel(task);}, 1000); +async function taskpoolCancel(): Promise { + let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number + taskpool.execute(task).then((res: number)=>{ + console.log("taskpool test result: " + res); + }).catch((err: string) => { + console.log("taskpool test occur error: " + err); + }); + // 1s后取消task + setTimeout(()=>{ + taskpool.cancel(task);}, 1000); } taskpoolCancel(); @@ -838,37 +816,38 @@ taskpoolCancel(); ```ts // 已执行的任务取消失败 @Concurrent -function inspectStatus(arg) { - // 第一时间检查取消并回复 - if (taskpool.Task.isCanceled()) { - return arg + 2; - } - // 延时2s - let t = Date.now(); - while (Date.now() - t < 2000) { - continue; - } - // 第二次检查取消并作出响应 - if (taskpool.Task.isCanceled()) { - return arg + 3; - } - return arg + 1; +function inspectStatus(arg: number): number { + // 第一时间检查取消并回复 + if (taskpool.Task.isCanceled()) { + return arg + 2; + } + // 延时2s + let t: number = Date.now(); + while (Date.now() - t < 500) { + continue; + } + // 第二次检查取消并作出响应 + if (taskpool.Task.isCanceled()) { + return arg + 3; + } + return arg + 1; } -async function taskpoolCancel() { - let task = new taskpool.Task(inspectStatus, 100); // 100: test number - taskpool.execute(task).then((res)=>{ - console.log("taskpool test result: " + res); - }).catch((err) => { - console.log("taskpool test occur error: " + err); - }); - setTimeout(()=>{ - try { - taskpool.cancel(task); // 任务已执行,取消失败 - } catch (e) { - console.log("taskpool.cancel occur error:" + e); - } - }, 3000); // 延时3s,确保任务已执行 +async function taskpoolCancel(): Promise { + let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number + taskpool.execute(task).then((res: number)=>{ + console.log("taskpool test result: " + res); + }).catch((err: string) => { + console.log("taskpool test occur error: " + err); + }); + + setTimeout(()=>{ + try { + taskpool.cancel(task); // 任务已执行,取消失败 + } catch (e) { + console.log("taskpool.cancel occur error:" + e); + } + }, 3000); // 延时3s,确保任务已执行 } taskpoolCancel(); @@ -879,8 +858,8 @@ taskpoolCancel(); ```ts // 待执行的任务组取消成功 @Concurrent -function printArgs(args) { - let t = Date.now(); +function printArgs(args: number): number { + let t: number = Date.now(); while (Date.now() - t < 1000) { continue; } @@ -888,26 +867,26 @@ function printArgs(args) { return args; } -async function taskpoolGroupCancelTest() { - let taskGroup1 = new taskpool.TaskGroup(); +async function taskpoolGroupCancelTest(): Promise { + let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup1.addTask(printArgs, 10); // 10: test number taskGroup1.addTask(printArgs, 20); // 20: test number taskGroup1.addTask(printArgs, 30); // 30: test number - let taskGroup2 = new taskpool.TaskGroup(); - let task1 = new taskpool.Task(printArgs, 100); // 100: test number - let task2 = new taskpool.Task(printArgs, 200); // 200: test number - let task3 = new taskpool.Task(printArgs, 300); // 300: test number + let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup(); + let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number + let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number + let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number taskGroup2.addTask(task1); taskGroup2.addTask(task2); taskGroup2.addTask(task3); - taskpool.execute(taskGroup1).then((res) => { + taskpool.execute(taskGroup1).then((res: Array) => { console.info("taskpool execute res is:" + res); - }).catch((e) => { + }).catch((e: string) => { console.error("taskpool execute error is:" + e); }); - taskpool.execute(taskGroup2).then((res) => { + taskpool.execute(taskGroup2).then((res: Array) => { console.info("taskpool execute res is:" + res); - }).catch((e) => { + }).catch((e: string) => { console.error("taskpool execute error is:" + e); }); @@ -922,48 +901,48 @@ taskpoolGroupCancelTest() ```ts // 分别创建执行100个高、中、低优先级的任务,查看其各项信息 @Concurrent -function delay() { - let start = new Date().getTime(); +function delay(): void { + let start: number = new Date().getTime(); while (new Date().getTime() - start < 500) { continue; } } -let highCount = 0; -let mediumCount = 0; -let lowCount = 0; -let allCount = 100; +let highCount: number = 0; +let mediumCount: number = 0; +let lowCount: number = 0; +let allCount: number = 100; for (let i = 0; i < allCount; i++) { - let task1 = new taskpool.Task(delay); - let task2 = new taskpool.Task(delay); - let task3 = new taskpool.Task(delay); + let task1: taskpool.Task = new taskpool.Task(delay); + let task2: taskpool.Task = new taskpool.Task(delay); + let task3: taskpool.Task = new taskpool.Task(delay); taskpool.execute(task1, taskpool.Priority.LOW).then(() => { lowCount++; - }).catch((e) => { + }).catch((e: string) => { console.error("low task error: " + e); }) taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => { mediumCount++; - }).catch((e) => { + }).catch((e: string) => { console.error("medium task error: " + e); }) taskpool.execute(task3, taskpool.Priority.HIGH).then(() => { highCount++; - }).catch((e) => { + }).catch((e: string) => { console.error("high task error: " + e); }) } -let start = new Date().getTime(); +let start: number = new Date().getTime(); while (new Date().getTime() - start < 1000) { - continue; -} -let taskpoolInfo = taskpool.getTaskPoolInfo(); -let tid = 0; -let taskIds = []; -let priority = 0; -let taskId = 0; -let state = 0; -let duration = 0; + continue; +} +let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo(); +let tid: number = 0; +let taskIds: Array = []; +let priority: number = 0; +let taskId: number = 0; +let state: number = 0; +let duration: number = 0; for(let threadInfo of taskpoolInfo.threadInfos) { tid = threadInfo.tid; taskIds.length = threadInfo.taskIds.length; diff --git a/zh-cn/application-dev/reference/apis/js-apis-worker.md b/zh-cn/application-dev/reference/apis/js-apis-worker.md index 2911e4d101..bdcaa44e32 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-worker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-worker.md @@ -2083,17 +2083,6 @@ Worker基于Actor并发模型实现。在Worker的交互流程中,JS主线程 Actor并发模型的交互原理:各个Actor并发地处理主线程任务,每个Actor内部都有一个消息队列及单线程执行模块,消息队列负责接收主线程及其他Actor的请求,单线程执行模块则负责串行地处理请求、向其他Actor发送请求以及创建新的Actor。由于Actor采用的是异步方式,各个Actor之间相互隔离没有数据竞争,因此Actor可以高并发运行。 -### 注意事项 -- Worker存在数量限制,当前支持最多同时存在8个Worker。 -- 在API version 8及之前的版本,当Worker数量超出限制时,会抛出错误Error "Too many workers, the number of workers exceeds the maximum."。 -- 从API version 9开始,当Worker数量超出限制时,会抛出错误BusinessError "Worker initialization failure, the number of workers exceeds the maximum."。 -- 主动销毁Worker可以调用新创建Worker对象的terminate()或workerPort.close()方法。 -- 自API version 9版本开始,若Worker处于已经销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的BusinessError。 -- Worker的创建和销毁耗费性能,建议管理已创建的Worker并重复使用。 -- 创建Worker工程时,new worker.Worker构造函数和new worker.ThreadWorker构造函数不能同时使用,否则将导致工程中Worker的功能异常。自API version 9版本开始,建议使用[new worker.ThreadWorker](#constructor9)构造函数,在API version 8及之前的版本,建议使用[new worker.Worker](#constructordeprecated)构造函数。 -- 创建Worker工程时,在Worker线程的文件中(比如本文中worker.ts)不能导入任何有关构建UI的方法(比如ets文件等),否则会导致Worker的功能失效。排查方式:解压生成的Hap包,在创建Worker线程的文件目录中找到"worker.js",全局搜索"View"关键字。如果存在该关键字,说明在worker.js中打包进去了构建UI的方法,会导致Worker的功能失效,建议在创建Worker线程的文件中修改 "import “xxx” from src"中src的目录层级。 -- 线程间通信时传递的数据量最大限制为16M。 - ## 完整示例 > **说明:**
> 以API version 9的工程为例。
API version 8及之前的版本仅支持FA模型,如需使用,注意更换构造Worker的接口和创建worker线程中与主线程通信的对象的两个方法。 -- GitLab