Reputation: 8711
I am trying to write a cloud function that does the following:
The code below works fine until the last part that try to do the job no. 3. The error message is 'Function returned undefined, expected Promise or value'.
I think this is a syntax problem specific to Firebase. Could someone point me to the right syntax to use to do the task?
Thanks a lot!
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
})
})
});
Upvotes: 0
Views: 427
Reputation: 83093
You need to return the first Promise in the Promises chain, i.e. the Promise returned by the once()
method, as follows:
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
})
})
});
I would suggest you watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/
Upvotes: 2