首页 > 解决方案 > 仅接收发送的最后一条消息(Firebase 云消息传递)

问题描述

我试图使用firebase admin sdk从firebase云功能向一个主题发送多条消息。但是如果设备没有连接到网络,那么我打开网络连接我只会收到我onMessageReceived()在我的 android 应用程序内部方法发送的最后一条消息。我想接收设备未连接到互联网时发送的所有消息。

我的云功能代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.showNotification = functions.https.onCall((data,context) => {

  var topic = 'weather';

  var message = {
    data: {
      title: 'This is title',
      description: getRandomString(15)
    },
    topic: topic,
    android : {
        ttl : 86400
    }
  };

  // Send a message to devices subscribed to the provided topic.
  admin.messaging().send(message)
    .then((response) => {
      // Response is a message ID string.
      console.log('Successfully sent message:', response);
      return response;
    })
    .catch((error) => {
      console.log('Error sending message:', error);
    });

});

标签: javascriptandroidfirebasefirebase-cloud-messaginggoogle-cloud-functions

解决方案


可调用函数必须从函数回调的顶层返回一个promise,该函数解析为要发送给客户端的数据。现在,您的函数什么也不返回,这意味着它立即终止并且什么也不返回。return response代码实际上只是从回调函数返回一个值,而then不是顶级函数。试试这个,它应该将该值传播到函数之外并传播到客户端。

  return admin.messaging().send(message)
    .then((response) => {
      // Response is a message ID string.
      console.log('Successfully sent message:', response);
      return response;
    })
    .catch((error) => {
      console.log('Error sending message:', error);
    });

在函数代码中正确处理 Promise 非常重要,否则它们可能根本不起作用。


推荐阅读