我想創建一個使用jquery和firebase的註冊系統,而我遇到問題的問題是不知道'調用firebase'返回的內容。讓我告訴你在我的代碼:Javascript和Firebase 3 - 使用電子郵件和密碼創建用戶
HTML(通過去除不相關的代碼簡化):
<div id="registerForm">
<input type="text" id="userEmail" placeholder="Email">
<input type="password" id="userPass" placeholder="Password">
<button type="button" id="register">Register</button>
</div>
JQuery的(再次,僅表示對於火力地堡和註冊代碼):
<script src=" /* Jquery url */ "></script>
<script src=" /* Firebase url */ "></script>
<script>
// Initialize Firebase
var config = {
apiKey: "*my api key*",
authDomain: "*myProject*.firebaseapp.com",
databaseURL: "https://*myProject*.firebaseio.com",
storageBucket: "*myProject*.appspot.com",
};
firebase.initializeApp(config);
</script>
<script>
$('#register').click(function() {
var email = $('#userEmail');
var pass = $('#userPass');
if(email.val() && pass.val()){
// this is where I stop knowing how all this firebase stuff works
firebase.auth().createUserWithEmailAndPassword(email.val(), pass.val()).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode + ' - ' + errorMessage);
});
// This is where it doesn't wanna work. Please check the first paragraph below
// for the explanation of how it doesn't work.
console.log('this message shouldn\'t show if there wasn\'t an error.'); //This fires before firebase.auth()... for some reason
if(error) {
console.log('there was an error');
} else {
console.log('everything went fine');
}
} else {
console.log('fill in both fields');
}
});
</script>
我想要一個if-else語句來檢查firebase.auth方法返回的內容。如果是錯誤,則顯示錯誤,如果不顯示成功消息並將其他用戶詳細信息存儲到userDetails數據庫表等,但無論我放在哪裏的代碼似乎都在firebase.auth方法之前執行。我認爲問題在於我不知道firebase的返回變量是如何調用的,以便我可以執行if(firebase.auth.success(或其他)){} else {}。
上述代碼有效,就像註冊成功,新用戶將顯示在firebase上一樣,如果出現錯誤,我可以打印並查看錯誤。問題只是不知道如何處理對firebase的成功/失敗調用,以及稍後寫入的代碼似乎在調用firebase之前執行的事實。
請忽略我可能犯的任何拼寫/語法錯誤,因爲它會將錯誤複製到SO而不是實際代碼中的錯誤。
任何幫助將不勝感激,謝謝!