Google Firebase Error(Function returned undefined, expected Promise or value)
Solution 1:
As Frank indicates in his comment on your post, the return statement that is producing the warning is this one:
if (post.sanitized) return;
The warning can be silenced by returning a dummy value (e.g. null, false, 0). The value is not used.
Earlier versions of Cloud Functions did not complain when a function exited using a return statement with no value. That explains why you see return;
in the video you linked and in the documentation. The comment on the question by Firebaser Frank van Pufeelen, explains why the change was made.
The simplest way to eliminate the warning is to add a return value, as Frank suggested:
if (post.sanitized) return 0;
Another option is to change the trigger from onWrite()
to onCreate()
. Then the function will not be invoked when the post is sanitized and the check that produces the warning is not needed:
exports.sanitizePost = functions.database
.ref('/test/{pushId}')
.onCreate(event => { // <= changed from onWrite()
const post = event.data.val();
//if (post.sanitized) return; // <= no longer needed
console.log('Sanitizing new post', event.params.pushId);
console.log(post);
//post.sanitized = true; // <= not needed when trigger is onCreate()
post.title = sanitize(post.title);
post.body = sanitize(post.body);
return event.data.ref.set(post);
});
Solution 2:
I was getting this same error for attempting to read a document using .get()
which returns a promise.
I found out in the official Firebase YouTube tutorial that to resolve this error, I needed to return the promise line of code. Check minute 4:18 in the tutorial linked video [https://youtu.be/d9GrysWH1Lc]
Also, as a side note, what lead me to the tutorial solution is when I noticed in the function logs did actually log valid values but only after the function is closed, even though the error says the result was undefined.
Solution 3:
Adding to what @bob-snyder said, your problem is that your returning undefined
under a condition.
if (post.sanitized) return;
My suggestion is to use a single exit point, which is a common tip when programming. Article.
Example
// code...
const SUCCESS_CODE = 0;
exports.sanitizePost = functions.database
.ref('/posts/{pushId}')
.onWrite(event => {
const post = event.data.val();
let response = Promise.resolve(SUCCESS_CODE);
if (!post.sanitized) {
console.log('Sanitizing new post', event.params.pushId);
console.log(post);
post.sanitized = true;
post.title = sanitize(post.title);
post.body = sanitize(post.body);
response = event.data.ref.set(post);
}
return response;
})