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

原文地址:https://www.cnblogs.com/sjj33sda/p/14338760.html