在Firebase函数中修改变量 [英] Modifying variable within firebase function

查看:37
本文介绍了在Firebase函数中修改变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我的程序尝试修改 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆