Firebase从函数返回输出 [英] Firebase return output from function
问题描述
我是firebase中的新成员,我试图在函数中传递 $ variable
来检查 $ variable $ c
函数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
});
$ b $ p
$ b 上面的函数工作正常,但当我更改 alert (snapshot.exists());
到 return snapshot.exists();
它不起作用。它只是返回undefined,它应该返回 true
或 false。
我怎样才能做到这一点?提前致谢
解决方案几乎Firebase所做的一切都是异步的。当你调用函数 ifExistWaybillNo
时,期望立即返回,而不是等待。所以在你的 databaseRef.orderByChild(waybill_no)
完成之前,调用该函数的语句已经决定返回是 undefined
。
解决这个问题的方法是传递一个回调函数并使用返回值。对此的精确解释在这里完成得非常好:。
你只需要重命名一些函数,并遵循那里使用的语法。
开始:
函数(waybill_no,callback){
等待(waybill_no).on('value',function(snapshot){
var truth = snapshot.exists();
callback(truth); // this将返回您的价值原始调用者
});请记住,几乎所有Firebase都是异步的。>
/ p>
I am new in firebase and I'm trying to pass a $variable
in a function to check if the $variable
is exists.
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
});
}
The above function work's fine but when I changed alert(snapshot.exists());
to return snapshot.exists();
it doesn't working. It just return undefined, which should return true
or false.
How can I do this? thanks in advance
解决方案 Almost everything Firebase does is asynchronous. When you call the function ifExistWaybillNo
it expects an immediate return, not to wait. So before your databaseRef.orderByChild("waybill_no")
is finished the statement that called the function has already decided the return is undefined
.
The way to fix this is by passing a callback function and using the return there. An exact explanation of this is done very well here: return async call.
You just need to rename some of the functions and follow syntax used there.
To start:
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
});
}
Remember, almost everything Firebase is asynchronous.
这篇关于Firebase从函数返回输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!