• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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中可能发生的异常。推荐使用示例如下。
18import { taskpool } from '@kit.ArkTS';
19
20@Concurrent
21async function testPromiseError() {
22  await new Promise<number>((resolve, reject) => {
23    resolve(1);
24  }).then(()=>{
25    throw new Error('testPromise Error');
26  })
27}
28
29@Concurrent
30async function testPromiseError1() {
31  await new Promise<string>((resolve, reject) => {
32    reject('testPromiseError1 Error msg');
33  })
34}
35
36@Concurrent
37function testPromiseError2() {
38  return new Promise<string>((resolve, reject) => {
39    reject('testPromiseError2 Error msg');
40  })
41}
42
43async function testConcurrentFunc() {
44  let task1: taskpool.Task = new taskpool.Task(testPromiseError);
45  let task2: taskpool.Task = new taskpool.Task(testPromiseError1);
46  let task3: taskpool.Task = new taskpool.Task(testPromiseError2);
47
48  taskpool.execute(task1).then((d:object)=>{
49    console.info('task1 res is: ' + d);
50  }).catch((e:object)=>{
51    console.info('task1 catch e: ' + e);
52  })
53  taskpool.execute(task2).then((d:object)=>{
54    console.info('task2 res is: ' + d);
55  }).catch((e:object)=>{
56    console.info('task2 catch e: ' + e);
57  })
58  taskpool.execute(task3).then((d:object)=>{
59    console.info('task3 res is: ' + d);
60  }).catch((e:object)=>{
61    console.info('task3 catch e: ' + e);
62  })
63}
64
65@Entry
66@Component
67struct Index {
68  @State message: string = 'Hello World';
69
70  build() {
71    Row() {
72      Column() {
73        Button(this.message)
74          .fontSize(50)
75          .fontWeight(FontWeight.Bold)
76          .onClick(() => {
77            testConcurrentFunc();
78            this.message = 'success';
79          })
80      }
81      .width('100%')
82    }
83    .height('100%')
84  }
85}
86