简体   繁体   English

Javascript代码按顺序运行

[英]Javascript code running in order

Im having issues with my JS code not running in order. 我在我的JS代码无法按顺序运行时遇到问题。 It skips to the if(!hadError) before it executes the catch when there is an error so that hadError is always equal to true. 当出现错误时,它将在执行catch之前跳至if(!hadError) ,以便hadError始终等于true。 I know is has to do with javascript and how it runs things simultaneously but im not sure how to fix it. 我知道这与javascript及其如何同时运行事物有关,但我不确定如何解决。 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();
  }
}

Firebase methods are asynchronous and return Promise 's. Firebase方法是异步的,并返回Promise You can do a .then() on after the method call to execute code after the Promise is returned, eg 您可以在方法调用之后执行.then(),以在返回Promise之后执行代码,例如

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 . 根据方法的不同,您甚至可能不需要检查hadError

For further reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then 有关更多参考: https : //developer.mozilla.org/zh-CN/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. 在某些情况下,你可以通过第二个方法then是,如果叫Promise被拒绝,但火力地堡的方法,该API是指为catch错误处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM