harmony 鸿蒙验证示例代码同源–异常场景5

  • 2025-06-12
  • 浏览 (5)

验证示例代码同源–异常场景5

文档代码块中,id重复(但是引用的内容一致),验证扫描结果

doc此段代码将ID写错了

const promise: Promise<number> = 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);
})
async function myAsyncFunction(): Promise<string> {
  const result: string = await new Promise((resolve: Function) => {
    setTimeout(() => {
      resolve('Hello, world!');
    }, 3000);
  });
  console.info(result); // 输出: Hello, world!
  return result;
}

@Entry
@Component
struct PromiseAsyncAwait {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(async () => {
            let res = await myAsyncFunction();
            console.info('res is: ' + res);
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

嵌套的ID,docs中不含嵌套部分

import { BusinessError } from '@kit.BasicServicesKit';
promise.then((result: number) => {
  console.info(`Random number is ${result}`);
}).catch((error: BusinessError) => {
  console.error(error.message);
});

你可能感兴趣的鸿蒙文章

harmony 鸿蒙验证示例代码同源–异常场景1

harmony 鸿蒙验证示例代码同源–异常场景2

harmony 鸿蒙验证示例代码同源–异常场景3

harmony 鸿蒙验证示例代码同源–异常场景4

harmony 鸿蒙验证示例代码同源–正常场景

harmony 鸿蒙异步并发 (Promise和async/await)

harmony 鸿蒙多线程并发概述

harmony 鸿蒙TaskPool简介

0  赞