Reputation: 87
Im having issues with my JS code not running in order. It skips to the if(!hadError)
before it executes the catch when there is an error so that hadError is always equal to true. I know is has to do with javascript and how it runs things simultaneously but im not sure how to fix it.
Here is the code:
var email = $('#email').val();
var password = $('#password').val();
var hadError = false;
// var unlocked = false;
if(email != "" && password != ""){
auth.signInWithEmailAndPassword(email, password).catch(function(error) {
// console.log(hadError);
hadError = true;
console.log(hadError);
var errorCode = error.code;
var errorMessage = error.message;
$('#login-error').text(errorMessage);
// unlocked = true;
});
if(!hadError){
success();
}
}
Upvotes: 1
Views: 47
Reputation: 1002
Firebase methods are asynchronous and return Promise
's. You can do a .then() on after the method call to execute code after the Promise is returned, e.g.
auth.signInWithEmailAndPassword(email, password).then((user) => {
//if you want, do something with the `user` which is a firebase.User
if(!hadError) success();
}).catch(function(error) {
hadError = true;
console.log(hadError);
var errorCode = error.code;
var errorMessage = error.message;
$('#login-error').text(errorMessage);
});
Depending on the method you may not even need to check hadError
.
For further reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
In some cases you can pass a second method to then
that is called if the Promise
is rejected, but for Firebase the method that the API refers to is catch
for error handling.
Upvotes: 2