Firebase函数-admin.messaging().sendToTopic执行但从未进入`then`块 [英] Firebase Functions - admin.messaging().sendToTopic executes but never makes it to the `then` block

查看:166
本文介绍了Firebase函数-admin.messaging().sendToTopic执行但从未进入`then`块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For some reason the then block of an admin function doesn't seem to be executing - I don't see any of the console.log messages in the firebase console:

这是我所有的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块:

The code that isn't being executed is inside a messaging function call - I receive the message so it is at least getting that far, but it doesn't seem to get into the then block:

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日志中看到的所有内容:

This is all I see in the firebase functions log:

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

我还应该看到以下输出:

I should also see the output from:

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

至少...

发生了什么事?

推荐答案

您需要从函数中返回一个Promise,该Promise将在所有异步工作完成后进行解析.如果您不这样做,Cloud Functions可能会在工作完成之前终止您的功能.

You need to return a promise from your function that resolves when all the asynchronous work is complete. If you don't do that, Cloud Functions will terminate your function, possibly before the work is complete.

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

In your case, you should put a return keyword in front of admin.messaging()... instead of returning null.

阅读文档以获取更多信息,并观看我的视频系列,了解如何处理Cloud Functions中的承诺.

Please read the documentation for more information, and watch my video series on dealing with promises in Cloud Functions.

这篇关于Firebase函数-admin.messaging().sendToTopic执行但从未进入`then`块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆