【问题标题】:async, await not working as expected ionic异步,等待未按预期工作
【发布时间】:2019-04-19 18:57:34
【问题描述】:

试图弄清楚为什么这不起作用以及我缺少什么。

我正在从登录页面调用服务中的函数

this.comms.updateAccessedState();

内部服务

 async updateAccessedState() {
   console.log("get this token 1");
   await this.getToken();
   console.log(`3 ${this.token}`);
 }

getToken() {
this._currentUser.getProfile().then((data) => {
  console.log("retrieve token 2");
  this.token = data.token;
});

将其打印到控制台时

我收到get token => 1 3 undefined retrieving token => 2

为什么函数没有被“等待”

【问题讨论】:

    标签: angular ionic-framework async-await


    【解决方案1】:

    你需要让方法getTokenasync,并让它返回一个promise。改成这样:

    async getToken(): Promise<any> {
        return this._currentUser.getProfile().then((data) => {
          console.log("retrieve token 2");
          this.token = data.token;
        });
    

    【讨论】:

      【解决方案2】:

      我相信这也行得通。如果可能的话,我发现不将async/awaitthen 混合使用会更容易。

      async getToken() {
          let data = await this._currentUser.getProfile();
          console.log("retrieve token 2");
          this.token = data.token;
      });
      

      【讨论】:

        猜你喜欢
        • 2020-03-04
        • 2019-04-07
        • 2022-01-22
        • 2018-12-02
        • 1970-01-01
        • 2021-07-15
        • 2021-12-08
        • 2023-03-03
        • 2019-08-31
        相关资源
        最近更新 更多