繁体   English   中英

在Firebase函数中修改变量

[英]Modifying variable within firebase function

每当我的程序尝试修改firebase function exists时,获取的值都是临时的。 我希望能够在此function结束时return truefalse 。我看到了一些相关的文章,但似乎没有任何效果。 使exists global并分离snapshot function无效。 有什么建议吗?

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返回了一个承诺, then返回了一个新的承诺,您就不能只返回exists ,因为为其分配值的块是稍后发生的。

但是,您可以返回承诺, 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*/)

在这种情况下,由于范围的原因,您不能返回存在。 function(snapshot)后方括号中的所有内容都是回调,这意味着您的函数将查询设置为数据库,并在Firebase返回数据后在这些方括号中运行代码。 同时,它将继续您的其余功能。 因此在返回之前,不存在存在值。

您可能想要更全球化的东西。 您可以使existing成为全局变量,使该函数不返回任何内容,然后再检查existing的值。 如果必须对多个用户执行此操作,则可以将其放入字典类型的结构中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM