【问题标题】:Firebase Functions - admin.messaging().sendToTopic executes but never makes it to the `then` blockFirebase 函数 - admin.messaging().sendToTopic 执行但从未进入 `then` 块
【发布时间】:2019-02-24 00:28:17
【问题描述】:

由于某种原因,admin 函数的 then 块似乎没有执行 - 我在 firebase console 中看不到任何 console.log 消息:

这是我所有的firebase functions 代码:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
const firebaseHelper = require('firebase-functions-helper');
const serviceAccount = require('./serviceAccountKey.json');
var toPlainObject = require('lodash.toplainobject');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
//const firestore = require('firebase-firestore');

//firebaseHelper.firebase.initializeApp(serviceAccount, 'https://snag-b2b2d.firebaseio.com');

//if (!admin.apps.length) {
admin.initializeApp();
admin.firestore().settings({timestampsInSnapshots: true});
var db = admin.firestore();

function renameObjectKey(oldObj, oldName, newName) {
    const newObj = {};

    console.log("in renameObjectKey");

    Object.keys(oldObj).forEach(key => {
        const value = oldObj[key];

        if (key === oldName) {
            newObj[newName] = value;
        } else {
            newObj[key] = value;
        }
    });

    return newObj;
}

class ParamsObject {
    constructor(value, tempId) {
        this.data = {message: value, tempId: tempId};
    }
}

exports.sendMessageNotification = functions.firestore.document('messages/{messageId}').onWrite((change, context) => {

        // Get an object representing the document
        // e.g. {'name': 'Marie', 'age': 66}
        const newValue = change.after.data();

        // ...or the previous value before this update
        const previousValue = change.before.data();

        console.log("newValue:", newValue);

        console.log("messageIdChange:", context.params.messageId);
        //console.log("prevValue:", previousValue);

        // access a particular field as you would any JS property
        //const name = newValue.name;

        var topic = 'all';

        let params = toPlainObject(new ParamsObject(newValue[context.params.messageId].message, newValue[context.params.messageId].timestamp));
        //params.data = toPlainObject(new WebObject());

        /*var payload = {
          data: {
            message: newValue.data.message
          }
        };*/

        admin.messaging().sendToTopic(topic, params).then((response) => {
          console.log("Successfully sent message:", response);
          //console.log("Message ID:", response.messageId);

          var newObj = renameObjectKey(newValue, newValue[context.params.messageId].timestamp, response.messageId);

          console.log("newObj:", newObj);

          firebaseHelper.firestore.updateDocument(db, 'messages', newValue[context.params.messageId].timestamp, newObj);
        }).catch((error) => {
          console.log("Error sending message:", error);
        });

        return null;
      });

未执行的代码在 messaging 函数调用中 - 我收到了消息,所以它至少已经到了那么远,但它似乎没有进入 then 块:

admin.messaging().sendToTopic(topic, params).then((response) => {

          //*******DOESNT SEEM TO MAKE IT HERE*******

          console.log("Successfully sent message:", response);


          var newObj = renameObjectKey(newValue, newValue[context.params.messageId].timestamp, response.messageId);

          console.log("newObj:", newObj);

          firebaseHelper.firestore.updateDocument(db, 'messages', newValue[context.params.messageId].timestamp, newObj);
        }).catch((error) => {
          console.log("Error sending message:", error);
        });

这是我在firebase functions 日志中看到的全部内容:

2:43:14.793 PM
sendMessageNotification
Function execution took 682 ms, finished with status: 'ok'
2:43:14.508 PM
sendMessageNotification
messageIdChange: 1537382591952
2:43:14.497 PM
sendMessageNotification
newValue: { '1537382591952': { message: 'The relay seems to be malfunctioning.', name: 'eamon', timestamp: '1537382591952' } }
2:43:14.112 PM
sendMessageNotification
Function execution started

我还应该看到以下输出:

console.log("Successfully sent message:", response);

至少……

发生了什么?

【问题讨论】:

    标签: javascript firebase promise firebase-cloud-messaging google-cloud-functions


    【解决方案1】:

    您需要从您的函数中返回一个承诺,该承诺会在所有异步工作完成后解决。如果您不这样做,Cloud Functions 可能会在工作完成之前终止您的函数。

    在您的情况下,您应该在 admin.messaging()... 前面放置一个 return 关键字,而不是返回 null。

    read the documentation了解更多信息,请watch my video series on dealing with promises in Cloud Functions

    【讨论】:

    • 谢谢!我会尽量尝试,但似乎就是这样。
    • 这行得通 - 你知道为什么在添加 return 后函数会陷入循环吗?
    • 与退货无关。如果您更新触发您的函数的同一个文档,该函数将再次将其处理为另一个更改。您必须通过编写代码来处理这种情况,以检测更改是否不被处理,并提前返回。
    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    相关资源
    最近更新 更多