Javascript - IF running before time

4

Friends, could you explain me and if possible, give a solution to the following problem?

My if where it says:

if(aux == 0)
{
    console.log("não encontrado");
}

It is running before the check in firebase, this only the first time I open the application. Below is the code for my function:

var refUser = new Firebase("//endereçodofirebaseescondido");
var key;

function logar() {
  var aux = 0;
  var login = document.getElementById("form1").elements.namedItem("login").value;
  var pass = document.getElementById("form1").elements.namedItem("senha").value;
  refUser.orderByChild("login").equalTo(login).on("child_added", function(snapshot) {
    key = snapshot.key();
    refUser.orderByChild("pass").equalTo(pass).on("child_added", function(snap) {
      aux = 1;
      console.log(pass);
      if (key == snap.key()) {
        console.log("senha e login conferem");
      } else {
        console.log("não encontrado");
      }
    });
  });
  if (aux == 0) {
    console.log("não encontrado");
  }
}
    
asked by anonymous 30.03.2016 / 02:23

2 answers

2

It seems that you have not understood a fundamental point of Javascript, which are the asynchronous functions.

Notice that the code you want to execute before if belongs to an anonymous function that you passed as a parameter of the on call. This code will only be executed when child_added event occurs.

Everything between refUser. and second }); is a single command (think of it as a "line" only). This whole command simply records what will happen in the future. This record is instantaneous. Right after that, your if will run, because it comes right after that command. There is no time yet to happen for the child_added event that will trigger the code you want.

Your code is very confusing (I suggest you give your variable names a boost), so you can not suggest a new version, but when you understand exactly how asynchronous functions work, you will see that you have to change your to think.

    
30.03.2016 / 03:03
0

I was able to solve it! I used setTimeout to run if shortly thereafter, giving me time to run the code above.

Solution:

            setTimeout(function()
            {
                if(aux == 0)
                {
                    console.log("não encontrado");
                    alert("sem show");
                }
            }, 500)
    
30.03.2016 / 03:00