javascript - 仅接收最后发送的消息(Firebase 云消息传递)

标签 javascript android firebase firebase-cloud-messaging google-cloud-functions

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

我的云函数代码:

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);
    });

});

最佳答案

可调用函数必须从函数回调的顶层返回一个 promise ,该 promise 解析为要发送到客户端的数据。现在,您的函数不返回任何内容,这意味着它立即终止并且不返回任何内容。 返回响应代码实际上只是从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 非常重要,否则它们可能根本不起作用。

关于javascript - 仅接收最后发送的消息(Firebase 云消息传递),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58633860/

相关文章:

firebase - 将数据添加到 Firebase ID token

javascript - 如何使用数组获取选择框中的值

javascript - 如何访问 document.getElementsByClassName 的属性

javascript - TypeScript 可选回调参数与传递给它的匿名函数不匹配

android - 如何修复单击时错误的 alertDialog?

c# - 无法使用 Firebase 插入数据

javascript - 设置隐藏输入的值

android - 使用 super 用户构建 Android

java - android.app.RemoteServiceException android.app.ActivityThread$H.handleMessage 在 Playconsole 中收到此错误

javascript - Firebase+Javascript 将匿名帐户转换为永久帐户 - 错误 : response is not defined