我正在使用 Firebase 作为后端在 React 中进行一些身份验证。
我有一个函数可以检查用户是否存在并且可以按我的预期工作:
checkIfUserExists(uid) {
ref.child('users').child(uid).once('value', function(snapshot) {
if (snapshot.exists()) {
console.log("User exists");
return true;
} else {
console.log("User does not exist");
return false;
}
});
}
当我调用它并传递 uid 时,无论用户是否存在,它都会写入控制台。
this.checkIfUserExists(userId);
我只想获取用户是否登录的 bool 表示,但尝试执行类似的操作将始终打印“No user”。
if (this.checkIfUserExists(userId)) {
console.log('The user does really exist');
} else {
console.log('No user');
}
如果我尝试
console.log(this.checkIfUserExists(userId));
控制台输出“未定义”。
我是否以错误的方式处理这个问题?为什么它是未定义的?
最佳答案
内部函数内部的return语句不会通过外部函数返回值。相反,尝试发送这样的函数
checkIfUserExists(uid, callback) {
ref.child('users').child(uid).once('value', function(snapshot) {
callback.call(null, snapshot.exists());
});
};
checkIfUserExists(uid, function(exists){
if(exists){
console.log("User exists");
}else{
console.log("User does not exist");
}
});
关于javascript - 分配给变量时函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36673692/