3

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem, happy coding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.