简体   繁体   中英

Modifying variable within firebase function

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
}

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*/)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM