仅接收最后发送的消息(Firebase云消息)



我试图用firebase-admin-sdk从firebasecloud函数向主题发送多条消息。但如果设备没有连接到网络,那么我打开网络连接,我只会在我的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解析为要发送到客户端的数据。现在,您的函数什么都不返回,这意味着它立即终止,什么也不返回。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非常重要,否则它们可能根本不起作用。

最新更新