我正在尝试编写一个执行以下操作的云函数:
下面的代码可以正常工作,直到尝试执行此工作的最后一部分为止。 3.错误消息是“函数返回了未定义的,预期的承诺或价值”。
我认为这是Firebase特有的语法问题。有人可以指出我要用于执行任务的正确语法吗?
非常感谢!
exports.commentsupdate = functions.database.ref('posts/{postid}/comments/{commentsid}/')
.onCreate((snapshot,context) => {
const uid=snapshot.val()['uid'];
let username="";
let nickname="";
let profile_picture="";
const ref1=database.ref('users/'+uid);
ref1.once('value',function(ssnapshot){
username=ssnapshot.val()['username'];
nickname=ssnapshot.val()['nickname'];
profile_picture=ssnapshot.val()['profile_picture'];
}).then(()=>{
return snapshot.ref.update({
username:username,
nickname:nickname,
profile_picture:profile_picture
})
})
});
答案 0 :(得分:2)
您需要返回 Promises链中的第一个Promise,即once()
方法返回的Promise,如下所示:
exports.commentsupdate = functions.database.ref('posts/{postid}/comments/{commentsid}/')
.onCreate((snapshot, context) => {
const uid = snapshot.val()['uid'];
let username = "";
let nickname = "";
let profile_picture = "";
const ref1 = database.ref('users/' + uid);
return ref1.once('value') // <--- Note the return here
.then(snapshot => {
username = snapshot.val()['username'];
nickname = snapshot.val()['nickname'];
profile_picture = snapshot.val()['profile_picture'];
return snapshot.ref.update({
username: username,
nickname: nickname,
profile_picture: profile_picture
})
})
});
我建议您观看Firebase视频系列中有关“ JavaScript承诺”的3个视频:https://firebase.google.com/docs/functions/video-series/