Reputation: 342
Whenever my program attempts to modify exists
in the firebase function
, the obtained value is temporary. I want to be able to return true
or false
at the end of this function
.I have seen a few related posts and nothing seems to be working. Making exists global
and separating the snapshot function
didnt work. Any advice?
function checkIfUserExists(userId) {
var exists;
var usersRef = firebase.database().ref("users");
usersRef.child(userId).once('value').then(function(snapshot) {
exists = (snapshot.val() !== null); // exists is true or false
userExistsCallback(userId, exists);
});
return exists; //exists is undefined
}
Upvotes: 0
Views: 69
Reputation: 7553
Since once
returns a promise, and then
returns a new promise, you can't just return exists
, since the block that assigns a value to it happens later.
You can, however, return the promise, and use then
in the call site
function checkIfUserExists(userId) {
var exists;
var usersRef = firebase.database().ref("users");
return usersRef.child(userId).once('value').then(function(snapshot) {
exists = (snapshot.val() !== null); // exists is true or false
return exists;
});
}
Then in the call site:
checkIfUserExists(userId).then(exists => /*do something*/)
Upvotes: 1
Reputation: 184
In this case, you cannot return exists because of the scope. Everything within the brackets after function(snapshot)
is a callback, which means that your function sets up this query to the database and will run the code in those brackets after Firebase returns with your data. In the meantime, it will continue with the rest of your function. So exists isn't given a value before the return.
You probably want something more global. You could make exists a global variable, make this function return nothing, and check the value of exists afterwards. If you have to do this for multiple users, you can put it in a dictionary type of structure.
Upvotes: 0