Because the if ... else is ignored

0

In this code I do not understand why the forward if is ignored because although there is an error in the authentication, it always goes to the main page regardless of whether the variable err is true.

entrar()
{ 
var err=false;

firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(function(result){
  console.log("exito");
  err=false
})
.catch(function(error) {
  console.log("error");
  console.log(error.code);
  console.log(error.message);
  err=true;
});

if (err){
console.log("error");}
else{
this.navCtrl.push(HomePage);}
}  

Someone explains to me that I am doing wrong.

    
asked by ctrl_alt_del 12.03.2018 в 18:40
source

1 answer

3

Already having a function then and err writing the logic of when it is satisfactory and when it gives error would be the following:

entrar(){ 
  var err=false;
  var _this = this; //guardamos la instancia
  firebase.auth().signInWithEmailAndPassword(this.email, 
  this.password).then(function(result){
    console.log("exito");
    err=false;
    _this.navCtrl.push(HomePage);
  })
  .catch(function(error) {
    console.log("error");
    console.log(error.code);
    console.log(error.message);
    err=true;
});

With respect to saving the instance this , usually this is the object that calls the function, either a javascript object or a DOM object, but when you use functions that call anonymous functions the scope of this context is the inside of the function that's why it gives you undefined .

I advise you to look for a tutorial about this in javascript, because it is a bit complicated to explain (at least for me), to learn it in practice will be to head-butt against the keyboard.

Some reference links

  

Context this in an Object

     

What Are Promises

    
answered by 12.03.2018 / 19:07
source