Javascript Angular-方法不等待从Firebase获取值

Javascript Angular-方法不等待从Firebase获取值,javascript,angular,typescript,firebase,firebase-realtime-database,Javascript,Angular,Typescript,Firebase,Firebase Realtime Database,我有一个类在其构造函数中调用以下方法: async fetchSSN() { this.userSSN = await firebase.database().ref(`allUsers/${this.currentUser}/SSN`).once('value'); this.userSSN = this.userSSN.val(); } 基本上,它从用户节点获取SSN的值,并将其存储为名为userSSN的全局变量 稍后,我有一个方法,它使用SSN的值从firebase请求新数据

我有一个类在其构造函数中调用以下方法:

async fetchSSN() {
   this.userSSN = await firebase.database().ref(`allUsers/${this.currentUser}/SSN`).once('value');
   this.userSSN = this.userSSN.val();
}
基本上,它从用户节点获取SSN的值,并将其存储为名为
userSSN
的全局变量

稍后,我有一个方法,它使用SSN的值从firebase请求新数据。例如:

async getLastDocument() {
   firebase.database().ref(`allSSN/${await this.userSSN}/lastDocument`);
}
我遇到了一个奇怪的问题,如果我从应用程序中的另一个类调用getLastDocument()方法,
await
将不会等待
this.userSSN
从自己类的构造函数中检索其值。它基本上会尝试从
allSSN/undefined/lastDocument
获取数据,这显然不是我想要的

我在这里做错了什么?如何避免这种情况?

编辑:

您不能等待构造函数中的承诺。您可以做的是:

// Now, this.userSSN is a reference to a Promise.
fetchSSN() {
   this.userSSN = firebase.database().ref(`allUsers/${this.currentUser}/SSN`).once('value');
}
然后:

async getLastDocument() {
   firebase.database().ref(`allSSN/${(await this.userSSN).val()}/lastDocument`);
}
这样,“服务员”在方法上,而不是在构造函数上


第一件事:

  • 根据,
    .val()
    返回值本身,因此
    this.userSSN
    是一个原语或对象(
    数字
    字符串
    ,等等)

  • 因此,
    getLastDocument
    不需要是
    async
    ,只要您不需要
    等待

  • 如果
    getLastDocument
    具有
    this.userSSN=undefined
    ,则表示您事先没有调用
    fetchSSN
    ,或者,我相信您的情况是,这些方法位于
    服务
    中,您可能在两个不同的
    模块
    中定义,使它们成为两个不同的实例,那么您就不会调用相同的
    this.userSSN


  • 您引用的代码实际上不能直接在构造函数中,因为构造函数不能是异步的。可能构造器正在启动代码,而不是等待它。如果是这样,您需要以某种方式向调用方传递一个承诺,以便调用方可以在调用
    getLastDocument
    之前等待。我不是直接调用fetchSSN()方法。我在类的构造函数中有它,我希望每当我引用该类中的方法时都会调用它。我只调用方法
    getLastDocument()
    ,我希望
    getLastDocument()
    方法尝试并等待获取一个值
    this.userSSN
    ,然后使用该值继续调用。当前,在方法fetchSSN()完成值的获取之前调用了方法
    getLastDocument()
    ,因此
    对于我的请求,userSSN
    未定义的。你能建议一个解决方法吗?