Reputation: 511
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
Upvotes: 3
Views: 1490
Reputation: 7947
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.
Upvotes: 2