firebase Function returned undefined, expected Pro

2019-08-25 11:28发布

Hi this is the code that I want too use to send friend request notification from one app to other android app.

but I am getting Function returned undefined, expected Promise or value error in functions console and also I am not getting the token value..

My code is below...

'use-strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const db = admin.firestore();

exports.sendNotification = functions.firestore
    .document("users/{user_id}/notifications/{notification_id}")
    .onWrite((change,context)=>{

    const user_id = context.params.user_id;

    console.log("We have a notification to send to", user_id);

    var ref = db.collection('device_token').doc(user_id);
    var getDoc = cityRef.get().then(doc=>{
        if (!doc.exists) {
            return console.log('No such document!');
        } else {
            console.log('Document data:', doc.data());

            const payload = {
                notification: {
                    title: "Text.",
                    body: "You have a new Friend Request!",
                    icon: "default"
                }
            }

            return admin.messaging().sendToDevice(tockenDoc, payload).then(response=>{

                return console.log("Notification sent : success");

            });

        }
    }).catch(err=>{
        console.log('Error getting document', err);
    });

});

2条回答
仙女界的扛把子
2楼-- · 2019-08-25 11:43

Functions that are triggered by background operations (such as the write to Firestore in your case) and that execute asynchronous operations (such as the write to sendToDevice() in your code), need to return either a value or a promise to make it clear when they are done. You're not returning anything, so Cloud Functions complains that it doesn't know when the code is done.

Since you're not using the getDoc variable anywhere, you might as well return that. The return admin.messaging().sendToDevice() from within there will bubble up, and give Cloud Functions the information it needs to know how long to keep your function's container alive.

return cityRef.get().then(doc=>{
    ...
}).catch(err=>{
    ...
});
查看更多
趁早两清
3楼-- · 2019-08-25 12:02

onWrite create one Promise, that Promise stored to getDoc,

You can return getDoc.

查看更多
登录 后发表回答