Javascript - IF running before time

Asked

Viewed 87 times

4

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

Man if where it is written:

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

It is running before check in firebase, this only the first time I open the application. Below is the code of 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");
  }
}
  • 1

    It’s not clear exactly what the problem is. You’re finding it odd to log in "not found", that’s it?

  • That’s it. I click the button and it automatically executes that last if. I would like a solution for that if only executed after the most above part is executed.

2 answers

2


It seems to me that you didn’t understand a fundamental point of Javascript, which are the asynchronous functions.

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

All that stands between refUser. and the second }); is a single command (think of it as a single "line"). This whole command simply records what will happen in the future. This record is instantaneous. Right after your if will rotate, because it comes right after this command. No time yet to happen the event child_added that will unleash the code you want.

Your code is very confusing (I suggest you improve the names of your variables), so you can not suggest a new version, but when you understand exactly how asynchronous functions work, you will see that you will have to change your way of thinking.

0

I managed to solve! I used a setTimeout to run if shortly afterwards, giving you time to run the code further above.

Solution:

            setTimeout(function()
            {
                if(aux == 0)
                {
                    console.log("não encontrado");
                    alert("sem show");
                }
            }, 500)
  • 2

    This is a bad idea. There is no guarantee that the call to Firebase will take exactly that long. I suggest you try to understand how asynchronous calls work instead of appealing to clock-wise gambiarras.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.