javascript - 仅接收发送的最后一条消息(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);
});
});
解决方案
可调用函数必须从函数回调的顶层返回一个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 非常重要,否则它们可能根本不起作用。
推荐阅读
- twilio - Twilio Function 帮助(使用 Twilio Functions 和 Google Sheets 构建社区 SMS 群聊)
- typescript - 如何使用对象的值在打字稿中定义新类型?
- javascript - 使用 lodash 将包含数组的对象数组转换为唯一的对象查找
- python - 为什么在 Python 1%2>>>1 或 5%6>>>5
- java - Jackson 序列化 BasicFileAttributes
- python - 向现有 np 数组添加维度
- git - 如何挑选具有不同祖先/父母的两个提交?
- python - 安装 Colorama 时出现 ImportError
- python - 如何仅打印最后一个输出?
- pandas - 将 pandas 数据帧传递给函数时,有没有办法让 ipython 自动完成?