简体   繁体   English

Firebase实时数据库快照不返回正确或错误

[英]Firebase Realtime Database Snapshot Not Returning True or False

The snapshot function I am using will not give me a value which will then not execute the code. 我正在使用的快照功能不会给我一个不会执行代码的值。

The database is all linked up and removing the if statement and snapshot check writes to the database. 数据库全部链接起来并删除if语句和快照检查写入数据库。 However, I want this to work as I do not want to reset the user variables so I need to check if it already exists. 但是,我希望这个工作,因为我不想重置用户变量,所以我需要检查它是否已经存在。

function createUserData(){
    var ref = firebase.database().ref("users/" + uid);
ref.once("value")
  .then(function(snapshot) {
        userExistCheck = snapshot.exists();
    });

    if (userExistCheck == false){
        displayName = document.getElementById("name-input").value;
        firebase.database().ref('users/' + uid).set({
        username: displayName,
        email: email,
        module1: false,
        module2: false,
        module3: false,
        module4: false,
        module5: false,
        module6: false
      });
        window.alert("working")
    }
    else{
        window.alert(uid);
    }
}

If the user doesn't exist it should add the user however it doesn't. 如果用户不存在,则应添加用户,但不应添加。 There is no output at all and the window alert for uid displays. 根本没有输出,并且显示uid的窗口警报。

This block 这个块

ref.once("value")
  .then(function(snapshot) {
        userExistCheck = snapshot.exists();
    });

is Asynchronous, so before it retrieves your data is executing this one 是异步的,所以在检索数据之前正在执行这个

 if (userExistCheck == false){
        displayName = document.getElementById("name-input").value;
        firebase.database().ref('users/' + uid).set({
        username: displayName,
        email: email,
        module1: false,
        module2: false,
        module3: false,
        module4: false,
        module5: false,
        module6: false
      });
        window.alert("working")
    }
    else{
        window.alert(uid);
    }

which will not update after the value is checked if exists or not, to solve this move your code 在检查值是否存在后不会更新,以解决此问题

function createUserData(){
    var ref = firebase.database().ref("users/" + uid);
ref.once("value")
  .then(function(snapshot) {
        userExistCheck = snapshot.exists();
 if (userExistCheck == false){
        displayName = document.getElementById("name-input").value;
        firebase.database().ref('users/' + uid).set({
        username: displayName,
        email: email,
        module1: false,
        module2: false,
        module3: false,
        module4: false,
        module5: false,
        module6: false
      });
        window.alert("working")
    }
    else{
        window.alert(uid);
    }
    });


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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