首页 > 解决方案 > 云函数firebase返回值始终为null?

问题描述

我在firebase中使用了云功能

功能思想是如果没有领导者,则为会话设置领导者,否则返回领导者的用户ID我使用javascript

即使我返回snapshot.val或函数接收的用户 id,它也总是返回 null

console.log(snapshot.val)给我[对象对象]

代码

exports.SetLeader = functions.https.onCall((data, context) => {
userID = data.ID
sessionID = data.text
sessionref = "/Sessions/".concat(sessionID);
sessionref = sessionref.concat("/Leader");

var db = admin.database();
var ref = db.ref(sessionref);
console.log("ID" + userID)


        ref.once("value", function (snapshot) {
            console.log("snapchot"+ snapshot.val()); //x
            if (snapshot.val() == null) {
                admin.database()
                    .ref(sessionref).update({ userID })
                console.log("inside if " + userID)
                return { leader: userID };
            }else{
               console.log("inside else " + snapshot.val())
                return { leader: snapshot.val()};
            }

        }, function (errorObject) {
            console.log("The read failed: " + errorObject.code);
        });

        });

这是我的代码

如果没有leader,则记录,设置新的leader并返回id 日志不是领导者

记录是否有领导,我需要返回他的 id 记录是否有领导者

标签: javascriptfirebasegoogle-cloud-functionsreturn-value

解决方案


正如Callable Cloud Functions 的文档中所解释的,“要在异步操作后返回数据,请返回一个承诺”。通过使用该once()方法的“回调版本”,您不会返回 Promise。

您应该使用“承诺版本”,如下所示:

return ref.once("value")
        .then(snapshot => {...});

此外,由于您必须处理不同的情况,根据快照的值,async/await在您的 Cloud Function 中使用它更具可读性。因此,以下应该可以解决问题(未经测试):

exports.SetLeader = functions.https.onCall(async (data, context) => {

    try {
        const userID = data.ID
        const sessionID = data.text
        const sessionref = `/Sessions/${sessionID}/Leader`  // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

        const db = admin.database();
        const ref = db.ref(sessionref);
        console.log("ID" + userID)

        const snapshot = await ref.once("value");
        console.log("snapchot" + snapshot.val());

        if (snapshot.val() == null) {
            await admin.database().ref(sessionref).update({ userID })
            console.log("inside if " + userID)
            return { leader: userID };
        } else {
            console.log("inside else " + snapshot.val())
            return { leader: snapshot.val() };
        }
    } catch (error) {
        // See https://firebase.google.com/docs/functions/callable#handle_errors
        // for more fine grained error management
        console.log(error);
        return null;;
    }

});

推荐阅读