问题的工作示例: https://padder-939bc.firebaseapp.com/
当用户尝试注册时,我要检查用户名是否已在数据库中使用。我有一个检查输入的用户名的函数,并根据是否已经使用了它返回true或false(为了澄清,此函数按预期工作)。
我的问题是,即使checkUsername函数返回true,if语句也不会执行,并且默认在else中运行代码。
注册表格:
signupFormButton.addEventListener('click', (e) => {
e.preventDefault();
//Get User Info
var formEmail = signupForm['register-email'].value;
var formPassword = signupForm['register-password'].value;
var confirmPassword = signupForm['confirm-password'].value;
var formUsername = signupForm['register-username'].value;
var formFirstName = signupForm['register-firstname'].value;
var formLastName = signupForm['register-lastname'].value;
//force username to be lowercase
formUsername.toLowerCase();
if (checkUsername(formUsername)) {
//Register in Firebase
auth.createUserWithEmailAndPassword(formEmail, formPassword).then(cred => {
var userID = cred.user.uid;
//Store user in users database
database.collection('users').doc(cred.user.uid).set({
email: formEmail,
username: formUsername,
firstname: formFirstName,
lastname: formLastName,
displayName: ""
});
//Store username with userID in usernames database
return database.collection('usernames').doc(formUsername).set({
userID: userID
})
}).then(() => {
$('#modal-register').modal('hide');
signupForm.reset();
});
}
else{
usernameValText.style.color = 'white';
console.log('user was not valid');
}
});
checkUsername:
function checkUsername(checkUser) {
var usernameRef = database.collection('usernames').doc(checkUser);
console.log(checkUser);
usernameRef.get().then((docSnapshot) => {
if (docSnapshot.exists){
usernameRef.onSnapshot((doc) => {
console.log('user is not valid');
usernameValText.innerHTML = 'That username is unavailable';
usernameValText.style.color = 'red';
return false;
});
}
else{
console.log('user is valid');
return true;
}
});
}
我在做什么错?输入正确的用户名后,如何确保用户正确注册了网站,而不是已经注册了用户名,则该如何确保用户正确注册了网站?
出于测试目的,已经使用了用户名“ peter”。