繁体   English   中英

函数没有使用async / await以正确的顺序触发

[英]Functions not firing in correct order with async / await

在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

向getListKey添加一个return语句以返回promise。 否则,您将返回undefined,等待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 => {...})
  ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM