每当我的程序尝试修改 firebase 函数
中的exists
时,获得的值都是临时的。我希望能够在这个函数
结束时返回true
或false
。我看过一些相关的帖子,但似乎没有什么在职的。使存在全局
并分离快照功能
不起作用。有什么建议吗?
function checkIfUserExists(userId) {
var exists;
var usersRef = firebase.database().ref("users");
usersRef.child(userId).once('value').then(function(snapshot) {
exists = (snapshot.val() !== null); // exists is true or false
userExistsCallback(userId, exists);
});
return exists; //exists is undefined
}
最佳答案
由于 once
返回一个 Promise,并且 then
返回一个新的 Promise,因此您不能只返回 exists
,因为分配的 block 它的值稍后发生。
但是,您可以返回 promise ,并在调用站点中使用 then
function checkIfUserExists(userId) {
var exists;
var usersRef = firebase.database().ref("users");
return usersRef.child(userId).once('value').then(function(snapshot) {
exists = (snapshot.val() !== null); // exists is true or false
return exists;
});
}
然后在调用站点中:
checkIfUserExists(userId).then(exists => /*do something*/)
关于javascript - 修改firebase函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45742362/