【问题标题】:How to get a function to wait for the data to load from a second function before executing in angular如何让函数等待数据从第二个函数加载,然后再以角度执行
【发布时间】:2019-10-19 00:21:50
【问题描述】:

我只是不明白 async/await 是如何工作的;这就是我认为的问题所在。我正在尝试将数据从我的服务加载到我的组件,但我得到一个未定义的。但是正确的数据从我正在调用的函数中正确加载。我想这是一种重新构造代码以便 async/await 工作的方法,但我不知道如何。

不幸的是,关于 async/await 的教程让我更加困惑。

我尝试过将 async/await 放在不同的地方,但坦率地说,我不知道自己在做什么。

这是我的组件中的函数从我的 UserService 调用另一个函数

async onSubmit() {
    console.log(await this.userservice.currentusercountry());
  }

这是我的 userService 中的函数

async currentusercountry() {
    let x;
    this.currentuser().subscribe(value => {
      console.log(value.country.toString());
      x = value.country.toString()
    });
    await console.log(x);
    return x;
  }

我希望在我的 console.log 中得到类似的东西

India         user.service.ts:65 
India         user.service.ts:68 
India         pg.component.ts:43 

但是我得到了

undefined     user.service.ts:68 
undefined     pg.component.ts:43 
India         user.service.ts:65

【问题讨论】:

    标签: angular async-await


    【解决方案1】:

    你可以这样试试

    async onSubmit() {
    
        let data = await this.userservice.currentusercountry();
        console.log(data);
        console.log('works!!!!!');
    }
    

    用户服务

    async currentusercountry() {
      return promise = new Promise ((resolve, reject) => {
        let x;
        this.currentuser().subscribe(value => {
          console.log(value.country.toString());
          x = value.country.toString()
          resolve(x); // here we are passing value to our component
        });
      });
    }
    
    

    【讨论】:

    • 从基于 observable 的配方到基于 promise 的配方的更简单方法是使用 toPromise()
    【解决方案2】:

    试试这个:

    async currentusercountry() {
        let x;
        this.currentuser().subscribe(value => {
          console.log(value.country.toString());
          x = value.country.toString();
      await console.log(x);
        return x;
        });
    
      }
    

    【讨论】:

      【解决方案3】:

      我会在 cmets 中解释为什么你的函数是如何工作的。

      async currentusercountry() {
          let x;  // declare some variable, its value is initially undefined
          this.currentuser().subscribe(value => { // everything inside subscription will 
            console.log(value.country.toString()); // be executed LATER
            x = value.country.toString()
          });
          await console.log(x); // this is executed instantly
          return x; // this is also executed instantly, with current value of x, i. e. undefined
        }
      

      解决方法如下:

      async currentusercountry() {
          const value = await this.currentuser().toPromise();
          const x = value.country.toString();
          console.log(x);
          return x;
      }
      

      【讨论】:

      • 我喜欢你的代码如何使用 toPromise();我假设它将“价值”变成“对象”? toPromise() 结合“await”究竟做了什么?它是否在运行下一行代码之前等待 Promise 完成(从而成为一个对象)?
      • 首先,评估this.currentuser().toPromise()。该表达式的值是一个承诺。然后this.currentuser().toPromise()awaited,就像任何常规承诺一样,它只是在下面加上this.currentuser().toPromise().then(/* the entire rest of the function */) 的语法糖。
      【解决方案4】:

      为什么不用RXJS switchMap

      例如:

      onSumit(){
        this.userService.currentUserContry().subscribe();
      }
      

      用户服务

      currentUserContry(){
        return this.currentUser().pipe(
          switchMap((res) => {
            const x = value.country.toString()
            return of(x);
          })
        )
      }
      

      【讨论】:

        【解决方案5】:

        让事情变得“更自然”。你有两个 Observables

        1. this.userservice.currentusercountry()
        2. this.currentuser()

        您可以使用 forkjoin 进行唯一订阅

        forkjoin([this.userservice.currentusercountry(),this.currentuser()])
                 .subscribe(res=>{
                    console.log(res[0]) //the response from currentuserCountry
                    console.log(res[1]) //the response from currentuser
                  })
        

        【讨论】:

          猜你喜欢
          • 2020-10-30
          • 2019-02-16
          • 2019-02-16
          • 1970-01-01
          • 2011-02-12
          • 2017-01-31
          • 2021-08-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多