0

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
}

2 Answers 2

1

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*/)
Sign up to request clarification or add additional context in comments.

2 Comments

Ok I am using it in a while loop so at the all site I would write what? checkIfUserExists(userId).then(exists => //how to return true or false)
If you're using it in a loop, you'll have many promises. You can use Promise.all to wait for all of them to finish, and get a collection of results.
0

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.

Comments

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.