在Angular中使用async-await特性

Promise 和回调函数是在 JavaScript 中编写异步代码的构建块。

在 Angular 应用程序中,我们可以使用 Rx.js 来利用 Observables、Subject、BehaviorSubject 等的强大功能,以优雅的方式编写异步代码。

随着最新版本的 ECMA Script 草案,JavaScript 开始支持“异步等待”功能。

ECMAScript 最新草案 (ECMA-262)

1. 什么是 Async-await

当 async 函数被调用,它返回一个 Promise。当 async 函数返回一个值,Promise 将 resolve 返回值。当 async 函数抛出异常或某个值的时候,Promise 将 reject 抛出的值。

async 函数可以包含一个 await 表达式,该表达式将等待异步函数的执行完成才处理下一条语句, 并将 Promise 的 resolve 的结果作为表达式的结果返回,然后恢复 async 函数的执行并返回 resolve 的值。

async 函数可以包含一个 await 表达式,该表达式暂停执行下一条语句, 并等待异步函数的执行完成并将 Promise 执行结果进行解析作为返回值,然后恢复 async 函数的执行并返回解析的值。

简而言之,您将有机会以同步方式编写异步代码。 这样讲有些抽象, 下面我们来看两个实例就清晰了.

2. 实例 1

让我们考虑一个简单的例子。一个函数,它返回一个 Promise,在两秒后解析并返回作为参数传递的值。

1
2
3
4
5
6
7
8
9

resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}

使用 Promise,我们可以使用“then”回调函数获取值。

1
2
3
4
5
6
getValueWithPromise() {
this.resolveAfter2Seconds(20).then(value => {
console.log(`promise result: ${value}`);
});
console.log('I will not wait until promise is resolved');
}

在上面的情况下,第 5 行的 console.log() 应在第 3 行的 console.log() 之前执行。这是 Promise 的基本性质。

现在让我们看看 async-await 的用法。

1
2
3
4
5
async getValueWithAsync() {
const value = <number>await this.resolveAfter2Seconds(20);
console.log(`async result: ${value}`);
}

这里有几点需要注意:

  • 第 1 行 — 函数以“async”关键字为前缀。如果您的函数具有“await”关键字,则必须使用此前缀。这意味着整个函数还是异步执行, 不会阻塞调用它的主进程. 但是函数内部会有阻塞等待. 这样也非常合理, 毕竟远程调用, 文件读取之类的操作是受到硬件以及网络性能影响, 这部分等待时间是很难从软件层面避免的.

  • 第 2 行 — 我们没有在 Promise 函数之后调用“.then()”回调函数。相反,我们在函数调用前加上“await”关键字。该关键字不允许在 resolveAfter2Seconds 结束前执行下一个代码块。这意味着,只有当第 2 行的 Promise 得到解析后,第 3 行的 console.log() 才会被打印,就像同步函数调用一样。

  • 由于我们使用的是 Typescript,因此我们需要将 Promise 返回值类型转换为特定类型,因此第 2 行的 <number> 。

3. 实例 2

让我们尝试使用基于承诺的方法将两个数字相加。

1
2
3
4
5
6
7
8
9
10
11
12

addWithPromise() {
this.resolveAfter2Seconds(20).then(data1 => {
let result1 = <number>data1;
this.resolveAfter2Seconds(30).then(data2 => {
let result2 = <number>data2;
this.additionPromiseResult = result1 + result2;
console.log(`promise result: ${this.additionPromiseResult}`);
});
});
}

在现实世界的应用程序中,最终陷入嵌套的 Promise-then 代码结构(回调地狱)是很常见的。通过 2 层嵌套,我们得到了上面的代码。想象一下 7-8 层嵌套,其中包含捕获的变量和异常(如果有)。这很可怕不是吗?

现在采用基于异步的方法。

1
2
3
4
5
6
7
8

async addWithAsync() {
const result1 = <number>await this.resolveAfter2Seconds(20);
const result2 = <number>await this.resolveAfter2Seconds(30);
this.additionAsyncResult = result1 + result2;
console.log(`async result: ${this.additionAsyncResult}`);
}

两种方法都会给我们相同的结果,但就代码可读性而言, 代码的简单程度,维护“async-await”优于经典的 Promise-then 方法。

4. 使用 Http REST APIs

到目前为止我们讨论了简单的例子。在 Angular 应用程序中,我们可以使用 Http(即将废弃)或 HttpClient 服务来获取 REST 数据。默认情况下,HttpClient 类的“get()”、“put()”、“delete()”和“post()”方法返回Observable<T>。该结果集可以通过“subscribe”方法或使用 RxJs 中的“toPromise()”运算符来使用。

4.1. 使用 Observable 获取 HttpClient 结果

我见过许多 Angular 开发者使用“subscribe”来获取 Http REST 数据,但不知道它与“promise”的区别。“subscribe”方法来自“Observable”对象。订阅后,只要“Observer”产生新数据,就会执行“subscribe”回调。而 Promise 的“then()”回调处理程序应最多执行一次。因此,除非您需要使用重复数据,否则不要使用“订阅”。请改用“toPromise()”。如果你注意到 Angular 官方文档中给出的示例;大量使用“toPromise”。

1
2
3
4
5
6
7
8
9

getDataUsingSubscribe() {
this.httpClient.get<Employee>(this.url).subscribe(data => {
this.subscribeResult = data;
console.log('Subscribe executed.')
});
console.log('I will not wait until subscribe is executed..');
}

4.2. 使用 toPromise 获取 HttpClient 结果

Rx.js 提供了一个名为“toPromise()”的运算符,可用于将Observeble<T>转换为 Promise。一旦转换,只要有数据,它的“then”块就会被执行。

1
2
3
4
5
6
7
8
9

getDataUsingPromise() {
this.httpClient.get<Employee>(this.url).toPromise().then(data => {
this.promiseResult = data;
console.log('Promise resolved.')
});
console.log('I will not wait until promise is resolved..');
}

4.3. 使用 async-await 获取 HttpClient 结果

使用 async-await 模式,我们既不需要“订阅”也不需要“then”。代码看起来非常简单明了。从“url”获取数据后,将执行第 3 行,Observerable<T> 转换为 Promise,Promise 被解析,数据存储在“asyncResult”成员变量中。

1
2
3
4
async getAsyncData() {
this.asyncResult = await this.httpClient.get<Employee>(this.url).toPromise();
console.log('No issues, I will wait until promise is resolved..');
}

4.4. Conditional programming

很多时候应用程序需要从一个 url 获取数据并使用条件来获取下一个数据。使用 Promise 代码应如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
getConditionalDataUsingPromise() {
this.httpClient.get<Employee>(this.url).toPromise().then(data => {
console.log('First Promise resolved.')
if (data.id > 5) {
let anotherUrl = 'http://dummy.restapiexample.com/api/v1/employee/23';
this.httpClient.get<Employee>(anotherUrl).toPromise().then(data => {
this.conditionalPromiseResult = data;
console.log('Second Promise resolved.')
});
}
});
}

使用 async-await 代码应如下所示:

1
2
3
4
5
6
7
8
9
10

async getConditionalDataUsingAsync() {
let data = await this.httpClient.get<Employee>(this.url).toPromise();
if (data.id > 5) {
let anotherUrl = 'http://dummy.restapiexample.com/api/v1/employee/23';
this.conditionalAsyncResult = await this.httpClient.get<Employee>(anotherUrl).toPromise();
}
console.log('No issues, I will wait until promise is resolved..');
}

5. Angular 系列文章

最新更新以及更多 Angular 相关文章请访问 Angular 合集 | 鹏叔的技术博客

6. 总结

总而言之,async-await 等待功能为我们提供了一种在 Angular 应用程序中编写异步代码的更好方法。

在Angular中使用async-await特性

https://pengtech.net/angular/angular_async-await.html

作者

鹏叔

发布于

2023-09-27

更新于

2024-07-10

许可协议

评论