IF函数运行,而不是ELSE

时间:2017-01-05 23:18:36

标签: javascript firebase firebase-authentication

有人可以告诉我为什么此功能的else无法运行,但if会这样做吗?还有什么东西使代码运行缓慢?以下是我的代码。

function SignUserIn() {
// Get elements
const Email = document.getElementById("txtEmail");
const Password = document.getElementById("txtPassword");

// Get email and pass
const email = Email.value;
const password = Password.value;
const auth = firebase.auth();

//Sign In
firebase.auth().signInWithEmailAndPassword(email, password)
    .catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        if (errorCode === 'auth/wrong-password' || errorCode === 'auth/invalid-email' || errorCode === 'auth/user-disabled' || errorCode === 'auth/user-not-found') {
            window.alert(errorMessage);
            document.getElementById("txtPassword").value = "";
        }
        else {
            //Realtime listener
            firebase.auth().onAuthStateChanged(frebaseUser => {
                sessionStorage.setItem("email", email);
                window.alert("You Are Successfully Signed In! Welcome " + email);
                window.location = "homepage.html";
            });
        }

    });
}

1 个答案:

答案 0 :(得分:3)

.catch()方法仅在拒绝承诺时运行。如果您希望在承诺解决或被拒绝时运行代码,则应使用.then()。它需要两个函数参数,一个用于成功,另一个用于拒绝。

firebase.auth().signInWithEmailAndPassword(email, password)
    .then(function() {
        // Handle success here
        firebase.auth().onAuthStateChanged(frebaseUser => {
            sessionStorage.setItem("email", email);
            window.alert("You Are Successfully Signed In! Welcome " + email);
            window.location = "homepage.html";
        });
    }, function(error) {
        // Handle Errors here.
        var errorMessage = error.message;
        window.alert(errorMessage);
        document.getElementById("txtPassword").value = "";
    });