在Firebase函数中修改变量 [英] Modifying variable within firebase function
问题描述
每当我的程序尝试修改 firebase函数
中的 exists
时,所获得的值都是临时的.我希望能够在此函数
的结尾处返回true
或 false
.在职的.使 exists全球存在
和分离 snapshot函数
无效.有什么建议吗?
Whenever my program attempts to modify exists
in the firebase function
, the obtained value is temporary. I want to be able to return true
or false
at the end of this function
.I have seen a few related posts and nothing seems to be working. Making exists global
and separating the snapshot function
didnt work. Any advice?
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
}
推荐答案
由于一次
返回一个诺言,而 then
返回一个新的诺言,您不能仅仅返回存在
,因为为其分配值的块稍后发生.
Since once
returns a promise, and then
returns a new promise, you can't just return exists
, since the block that assigns a value to it happens later.
但是,您可以退还诺言,并在呼叫站点中使用 then
You can, however, return the promise, and use then
in the call site
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*/)
这篇关于在Firebase函数中修改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!