查看: 53|回覆: 0

Angular 同步async、await 使用方式

[複製鏈接]

3

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2010-11-30
發表於 2021-1-28 11:18:00 | 顯示全部樓層 |閲讀模式

理解 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 修饰要发送的异步请求



来源:https://www.cnblogs.com/sjj33sda/p/14338760.html
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部