查看: 36|回复: 0

Angular 同步async、await 使用方式

[复制链接]

0

主题

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.

在本版发帖返回顶部