firebase函数返回的值未定义,预期的承诺或价值

人气:537 发布:2022-10-16 标签: javascript node.js firebase google-cloud-firestore google-cloud-functions

问题描述

这是我也想用来从一个应用程序向另一个android应用程序发送好友请求通知的代码.

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

但我正在获取功能返回的undefined,预期的承诺或价值 功能控制台中出现错误,并且我也没有获得令牌值.

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);
    });

});

推荐答案

由后台操作(例如您的情况下对Firestore的写操作)触发并执行异步操作(例如对以下示例中的sendToDevice()的写操作)触发的功能您的代码),则需要返回一个值或一个诺言,以便在完成操作时将其弄清楚.您没有返回任何内容,因此Cloud Functions抱怨说它不知道代码何时完成.

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.

由于您没有在任何地方使用getDoc变量,因此最好将其返回.里面的return admin.messaging().sendToDevice()会冒出气泡,并向Cloud Functions提供所需的信息,以使其知道保持功能容器存活的时间.

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=>{
    ...
});

479