1/* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16// 并发异步函数中使用Promise 17// 并发异步函数中如果使用Promise,建议搭配await使用捕获Promise中可能发生的异常。推荐使用示例如下。 18// [Start concurrent_taskpool_async_promise_usage] 19import { taskpool } from '@kit.ArkTS'; 20 21@Concurrent 22async function testPromiseError() { 23 await new Promise<number>((resolve, reject) => { 24 resolve(1); 25 }).then(()=>{ 26 throw new Error('testPromise Error'); 27 }) 28} 29 30@Concurrent 31async function testPromiseError1() { 32 await new Promise<string>((resolve, reject) => { 33 reject('testPromiseError1 Error msg'); 34 }) 35} 36 37@Concurrent 38function testPromiseError2() { 39 return new Promise<string>((resolve, reject) => { 40 reject('testPromiseError2 Error msg'); 41 }) 42} 43 44async function testConcurrentFunc() { 45 const task1: taskpool.Task = new taskpool.Task(testPromiseError); 46 const task2: taskpool.Task = new taskpool.Task(testPromiseError1); 47 const task3: taskpool.Task = new taskpool.Task(testPromiseError2); 48 49 taskpool.execute(task1).then((d: object) => { 50 console.info(`task1 res is: ${d}`); 51 }).catch((e: object) => { 52 console.error(`task1 catch e: ${e}`); // task1 catch e: Error: testPromise Error 53 }) 54 taskpool.execute(task2).then((d: object) => { 55 console.info(`task2 res is: ${d}`); 56 }).catch((e: object) => { 57 console.error(`task2 catch e: ${e}`); // task2 catch e: testPromiseError1 Error msg 58 }) 59 taskpool.execute(task3).then((d: object) => { 60 console.info(`task3 res is: ${d}`); 61 }).catch((e: object) => { 62 console.error(`task3 catch e: ${e}`); // task3 catch e: testPromiseError2 Error msg 63 }) 64} 65 66@Entry 67@Component 68struct Index { 69 @State message: string = 'Hello World'; 70 71 build() { 72 Row() { 73 Column() { 74 Button(this.message) 75 .fontSize(50) 76 .fontWeight(FontWeight.Bold) 77 .onClick(() => { 78 testConcurrentFunc(); 79 // [StartExclude concurrent_taskpool_async_promise_usage] 80 this.message = 'success'; 81 // [EndExclude concurrent_taskpool_async_promise_usage] 82 }) 83 } 84 .width('100%') 85 } 86 .height('100%') 87 } 88} 89// [End concurrent_taskpool_async_promise_usage]