Angular 同步async、await 使用方式
<p>理解 async/await<br><br>
Angular 请求同步async、await使用方式<br>
<br>
<strong>promise, async和await</strong><br>
场景:发送前端一个请求,在获取到响应以后,将数据存入localstorage,然后跳转页面。<br>
问题:由于请求是异步的,所以可能存在先跳转了页面,数据才从服务器返回的情况。通过硬编码的方式可能会写很多层回调函数。</p>
<pre><code>mainFunction(item) {
this.subFunction(item.id).then(() => { //如果有返回值,()这里可以写
this.storage.set('xxx', this.xxx);
this.navToOtherPage()//在subFunction执行完成,返回结果后,进行后续操作
})
}
</code></pre>
<pre><code>async subFunction( Id: string) {
await this.xxxService.getxxxxx(Id).toPromise()
.then((response) => {
this.xxx = response.xxxxx
}).catch((err) => {
console.log(err)
});
}
</code></pre>
<p>需要同步调用的最外层函数中使用 async 修饰。 在方法体中,使用 await 修饰要发送的异步请求</p><br><br>
来源:https://www.cnblogs.com/sjj33sda/p/14338760.html
頁:
[1]