Firebase return 函数输出

Firebase return output from function

我是 firebase 的新手,我正在尝试在函数中传递 $variable 以检查 $variable 是否存在。

function ifExistWaybillNo(waybill_no)
{
  var databaseRef = firebase.database().ref('masterlist');
  databaseRef.orderByChild("waybill_no").equalTo(waybill_no).on('value', function(snapshot){
    alert(snapshot.exists()); //Alert true or false
  });
}

上面的功能工作正常,但是当我将 alert(snapshot.exists()); 更改为 return snapshot.exists(); 时,它不起作用。它只是 return 未定义,应该 return truefalse.

我该怎么做?提前致谢

Firebase 所做的几乎所有事情都是异步的。当您调用函数 ifExistWaybillNo 时,它期望立即 return,而不是等待。所以在你的 databaseRef.orderByChild("waybill_no") 完成之前调用函数的语句已经决定 return 是 undefined.

解决这个问题的方法是传递一个回调函数并在那里使用 return。对此的确切解释在这里做得很好:return async call.

您只需重命名一些函数并遵循那里使用的语法。

开始:

function(waybill_no, callback) { 
    databaseRef.orderByChild("waybill_no").equalTo(waybill_no).on('value', function(snapshot) {
    var truth = snapshot.exists();
    callback(truth); // this will "return" your value to the original caller
  });
}

记住,几乎所有 Firebase 都是异步的。