Angular 同步async、await 使用方式


理解 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 修飾要發送的異步請求


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM