代码之家  ›  专栏  ›  技术社区  ›  Giesburts

即使使用if/else语句JS,Firebase也会进行多次调用

  •  1
  • Giesburts  · 技术社区  · 9 年前

    因此,数据库中的电子邮件检查进行得很顺利,它将输出警报,而且我能够检索数据。但问题在于,当我输入一封不在数据库中的电子邮件时。当我输入一封新的电子邮件(和名称)时,它会检查数据库并返回false,但随后立即进行另一个调用(我不知道为什么,我想这是个问题),它会返回true,同时发出已经存在的警报。然后它将继续执行另一个函数来存储数据,因为这是第一个调用的输出(这是false)。

    checkForm() {
    
            let app = this;
    
            if (this.name == '' || this.emailadress == '') {
                alert('You have to fill out the form');
            } else {
    
                app.getFirebase();
    
            }
    },
    
    getFirebase() {
    
            let app = this;
    
            var ref = firebase.database().ref().child('/aanmeldingen/');
            ref.on('value', function(snapshot) {
    
                const array = [];
    
                snapshot.forEach(function(childSnapshot) {
                  var checkEmail = childSnapshot.val().email;
                  array.push(checkEmail);
                });
    
                const res = array.includes(app.emailadress);
                console.log(array);
                console.log(res);
    
                  if(res) {
                    alert('You already have entered the giveaway');
                  } else if (res == false) {
    
                    app.store();
    
                  }
            });
    },
    
    store() {
                    this.step_two = false;
                    this.active_two = false;
    
                    this.active_three = true;
                    this.step_three = true;
    
                    let app = this;
    
                    firebase.database().ref('/aanmeldingen/').push({
                    username: app.name,
                    email: app.emailadress,
                    });
    }
    

    控制台屏幕截图(输入Jane,不在数据库中)

    enter image description here

    1 回复  |  直到 9 年前
        1
  •  3
  •   Bob Snyder    9 年前

    你应该使用 once() 而不是 on() . on() store() 听众再次开火。

    推荐文章