Javascript Firebase云函数等待从数据库接收到异步数据

Javascript Firebase云函数等待从数据库接收到异步数据,javascript,firebase,firebase-realtime-database,Javascript,Firebase,Firebase Realtime Database,我想检查Firebase实时数据库中是否存在数据。问题是,在执行if(snapshot.exists())时,总是执行B,因为它是一个异步调用,所以没有值 ref.child("Users").child(theDataToAdd).once('value', function(snapshot) { if(snapshot.exists()) { //A }else{ //B } }); 如何实现等到if

我想检查Firebase实时数据库中是否存在数据。问题是,在执行
if(snapshot.exists())
时,总是执行B,因为它是一个异步调用,所以没有值

  ref.child("Users").child(theDataToAdd).once('value', function(snapshot) {
      if(snapshot.exists()) {
           //A
      }else{
          //B
      }

  });

如何实现等到if语句获得真/假值,然后继续执行代码?

不要使用once的callback参数。使用返回的承诺,并继续使用承诺

ref.child("Users").child(theDataToAdd).once('value').then(snapshot => {
    // do the next thing here
})
如果您不知道承诺是如何起作用的,请观看以下视频系列:


如果不完全理解承诺,就很难有效地使用云功能。

感谢您的回答。我得到了“Each then()应该返回一个值或抛出”错误。你必须花一些时间来学习承诺,否则我们将永远重复这个问题。
ref.child("Users").child(theDataToAdd).once('value').then(snapshot => {
    // do the next thing here
})