function isDisplayNameTaken(name) {
firebase
.database()
.ref()
.child("users")
.orderByChild("username")
.equalTo(name)
.once("value")
.then((snapshot) => {
return snapshot.exists();
});
}
我一直在尝试在注册用户之前检查用户名是否已经在数据库中,但是返回不起作用,函数(快照)内部的任何内容也没有更改其他全局变量来绕过它。
if(isDisplayNameTaken($userDisplayNameField.val())) {
numberOfChecksPassed += 1
}
这是不通过的条件。在过去的 5 个小时里,我已经完成了研究并一直在努力解决这个问题。提前致谢
首先,您不能像在简单的 if
语句中那样使用 promise 结果。您应该执行以下操作:
isDisplayNameTaken($userdisplayNameField.val()).then(taken => {
console.log('Is it taken?', taken);
});
在您使用简单的 if
的示例中 - if
语句将 promise 对象检查为其条件而不是已解析的值。
为此,isDisplayNameTaken
需要返回一个 promise (它没有)。
function isDisplayNameTaken(name) {
return firebase // Notice the return here.
.database()
.ref()
.child("users")
.orderByChild("username")
.equalTo(name)
.once("value")
.then((snapshot) => {
return snapshot.exists(); // This return will resolve the promise but you are not returning the resolved promise out of the function.
});
}