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

时间:2019-01-09 19:41:40

标签: javascript node.js firebase google-cloud-firestore google-cloud-functions

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

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

我的代码在下面...

'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 个答案:

答案 0 :(得分:1)

onWrite创建一个Promise,该Promise存储到getDoc

您可以返回getDoc

答案 1 :(得分:0)

由后台操作(例如您的情况下对Firestore的写入)触发并执行异步操作(例如您的代码中对sendToDevice()的写入)触发的函数需要返回一个值或一个承诺在完成时明确说明。您没有返回任何内容,因此Cloud Functions抱怨说它不知道代码何时完成。

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

return cityRef.get().then(doc=>{
    ...
}).catch(err=>{
    ...
});
相关问题