写点什么

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

作者:auhgnixgnahz
  • 2025-06-23
    北京
  • 本文字数:2093 字

    阅读完需:约 7 分钟

异步和多线程有啥区别?


原理


异步开发:异步编程以非阻塞的方式运行代码,当程序发起一个可能耗时的操作(如网络请求、文件读写)时,不会等待该操作完成,而是继续执行后续代码。待操作完成后,通过回调函数、Promise、async/await 等机制来处理结果。


多线程开发:多线程是指在一个程序中同时运行多个线程。这些线程可以并行执行不同的任务,共享进程的资源。


资源利用


异步开发:通常在单线程环境下运行,通过事件循环机制来处理多个任务。它避免了线程创建和切换的开销,因此资源消耗相对较少。


多线程开发:需要创建多个线程,每个线程都有自己的栈空间和上下文信息,因此会占用更多的系统资源。线程的创建和销毁也会带来一定的开销。


应用场景


异步开发:适合 I/O 密集型任务,如网络请求、文件读写等。


多线程开发:更适合 CPU 密集型任务,如复杂的计算、数据处理等。


Promise 提供了一个状态机制来管理异步操作的不同阶段,并提供了一些方法来注册回调函数以处理异步操作的成功或失败的结果。


const promise: Promise<number> = new Promise((resolve: Function, reject: Function) => {   //执行异步任务   //resolve返回成功结果  //reject 返回失败结果})</number>
复制代码


Promise 对象创建后,可以使用 then 方法和 catch 方法获取到回调结果


promise.then((result: number) => {  //成功回调结果}).catch((error: BusinessError) => {//失败回调结果});
复制代码


async/await 是一种用于处理异步操作的 Promise 语法糖,使得编写异步代码变得更加简单和易读。以下介绍 4 种异步的写法。


import { BusinessError } from "@kit.BasicServicesKit";import { showToast } from "../utils/ToastUtil";
@ObservedV2export class Student { @Trace name: string = '' @Trace age: number = 0 constructor(name: string, age: number) { this.name = name; this.age = age; }}
//和view数据结构解耦,不直接修改view的数据async function updateAge() { let stu: Student = await new Promise((resolve: Function, reject: Function) => { //模拟一个耗时3秒的任务 setTimeout(() => { let student: Student = new Student('Harmony', 20) resolve(student) }, 1000) }); return stu}@Entry@ComponentV2struct promisetest { @Local student: Student = new Student('HarmonyOS开发者笔记', 18) @Local normal:string = '刷新' //基础写法 通过promise执行异常任务之后,通过then方法和catch方法指定fulfilled状态和rejected状态的回调函数 updateName() { let promise: Promise<student> = new Promise((resolve: Function, reject: Function) => { //模拟一个耗时3秒的任务 setTimeout(() => { let student2: Student = new Student('HarmonyOS', 18) resolve(student2) }, 3000) }); promise.then((result: Student) => { this.student = result this.normal='刷新完成' }).catch((e:BusinessError)=>{ //处理reject返回的异常 }) //这段代码会优先执行 this.normal='刷新中。。。' } //async/await是一种用于处理异步操作的Promise语法糖,以同步的方式编写异步操作的代码 async update() { try { let stu: Student = await new Promise((resolve: Function, reject: Function) => { setTimeout(() => { if (this.student.age == 20) { reject(new Error('更新异常')); } let stu: Student = new Student('关注了吗', 18) resolve(stu) }, 1000) }) this.student=stu; } catch (e) { let er:Error = e showToast(er.message) } }
//指定返回类型,可以直接赋值给view async update2(): Promise<student> { let stu: Student = await new Promise((resolve: Function, reject: Function) => { //模拟网络请求耗时操作 setTimeout(() => { if (this.student.age == 18) { showToast('这里处理异常') reject(new Error('更新异常')); } let stu2: Student = new Student('OS', 22) //返回成功数据结构 resolve(stu2) }, 1000) }) return stu }
build() { Column({space:20}) { Text(this.student.name).fontSize(18) Text(this.student.age.toString()).fontSize(18) Button(this.normal).onClick(() => { this.updateName() }) Button('语法糖刷新').onClick(async () => { this.student = await updateAge() }) Button('刷新异常').onClick(() => { this.update() }) Button('异步回调刷新').onClick(async () => { this.student = await this.update2() }) }.width('100%').height('100%')
}}</student></student>
复制代码


运行演示:



发布于: 刚刚阅读数: 3
用户头像

auhgnixgnahz

关注

还未添加个人签名 2018-07-10 加入

还未添加个人简介

评论

发布
暂无评论
鸿蒙Next异步并发 (Promise和async/await)_鸿蒙Next_auhgnixgnahz_InfoQ写作社区