javascript - 云函数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);
});
});
解决方案
正如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;;
}
});
推荐阅读
- javascript - 我无法在 Reactjs 中 console.log() JSON 数据?
- php - 查找哪个 symfony 包与另一个 symfony 版本不兼容的方法
- r - 在带德文小数分隔符的引用 csv 文件上使用 colClass
- jsp - 使用 eclipse 3a 和 tomcat 9.0 的 jsp 和 servlets MVC 架构师
- angularjs - AngularJS - 选择框中的默认值
- imagemagick - 具有 4 个 (x,y) 坐标的 Imagemagick 倾斜图像
- javascript - Laravel 和 VueJS:在 Blade 中调用 VueJS 方法
- django-rest-framework - django rest 中的令牌身份验证失败
- javascript - 无法获取上下文元素文本
- javascript - 单击事件目标给出元素或其子元素,而不是父元素