理解 async/await
Angular 請求同步async、await使用方式
promise, async和await
場景:發送前端一個請求,在獲取到響應以后,將數據存入localstorage,然后跳轉頁面。
問題:由於請求是異步的,所以可能存在先跳轉了頁面,數據才從服務器返回的情況。通過硬編碼的方式可能會寫很多層回調函數。
mainFunction(item) {
this.subFunction(item.id).then(() => { //如果有返回值,()這里可以寫
this.storage.set('xxx', this.xxx);
this.navToOtherPage()//在subFunction執行完成,返回結果后,進行后續操作
})
}
async subFunction( Id: string) {
await this.xxxService.getxxxxx(Id).toPromise()
.then((response) => {
this.xxx = response.xxxxx
}).catch((err) => {
console.log(err)
});
}
需要同步調用的最外層函數中使用 async 修飾。 在方法體中,使用 await 修飾要發送的異步請求