【问题标题】:firebase Function returned undefined, expected Promise or valuefirebase 函数返回未定义的、预期的 Promise 或值
【发布时间】:2019-01-09 19:41:40
【问题描述】:

您好,这是我也想用来将好友请求通知从一个应用发送到其他 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);
    });

});

【问题讨论】:

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


    【解决方案1】:

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

    由于您没有在任何地方使用getDoc 变量,您不妨返回它。来自其中的return admin.messaging().sendToDevice() 会冒泡,并为 Cloud Functions 提供所需的信息,以了解让您的函数的容器存活多长时间。

    return cityRef.get().then(doc=>{
        ...
    }).catch(err=>{
        ...
    });
    

    【讨论】:

    • 感谢您的帮助,它对我有用......我也想知道我可以检索字段 os doc.data() 值是 {token : "vasdasdasd"} iant to store代币价值
    【解决方案2】:

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

    您可以返回getDoc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-05
      • 2019-08-06
      • 2018-06-12
      • 1970-01-01
      • 2018-04-18
      • 2018-12-03
      • 2019-11-03
      • 2019-08-12
      相关资源
      最近更新 更多