【问题标题】:Functions not firing in correct order with async / await使用 async / await 未按正确顺序触发的函数
【发布时间】:2019-05-27 08:12:32
【问题描述】:

在 Angular 服务中,我创建了以下函数:

getListKey(user) {
  firebase.database().ref(`userprofile/${user.uid}/list`).once('value').then(snapshot => {
    console.log(snapshot.val())
    this.listKey = snapshot.val()
    return this.listKey
  })
}

我想在加载时在另一个文件中调用此函数,并将返回的值分配给服务中的全局 listKey 变量,以用于组件中的另一个函数。但是,即使使用async/await,第二个函数也会在检索到数据之前触发。

这是我组件中的相关部分:

this.afAuth.authState.subscribe(async (user: firebase.User) => {
  await this.fire.getListKey(user);
  this.fire.getUserList(this.fire.listKey).subscribe(lists => {...})
  ...
}

如何让getUserList() 等待listKey

【问题讨论】:

    标签: javascript angular async-await


    【解决方案1】:

    在 getListKey 中添加 return 语句以返回 promise。否则,您将返回 undefined,并且 await undefined 不会等待数据库快照准备好。

    getListKey(user) {
      return firebase.database().ref(`userprofile/${user.uid}/list`).once('value').then(snapshot => {
        console.log(snapshot.val())
        this.listKey = snapshot.val()
        return this.listKey
      })
    }
    

    另外,您可能希望等待左侧:

    this.afAuth.authState.subscribe(async (user: firebase.User) => {
      const listKey = await this.fire.getListKey(user);
      this.fire.getUserList(listKey).subscribe(lists => {...})
      ...
    }
    
    

    【讨论】:

      猜你喜欢
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 2020-11-05
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      相关资源
      最近更新 更多