【问题标题】:Problem with messaging() in node.js for firebasenode.js中用于firebase的消息传递()问题
【发布时间】:2019-10-05 21:26:30
【问题描述】:

我想组织发送关于将文档添加到 Firestore 的推送通知。我正在为 node.js 使用来自 firebase 站点示例的代码。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
var message = {
    notification: {
        title: 'title!',
        body: 'body'
    },
    topic: "all"
};


exports.createRequest = functions.firestore
    .document('Requests/{RequestsId}')
    .onCreate((snap, context) => {
        console.log('We have a new request');
        // Send a message to devices subscribed to the provided topic.
        admin.messaging().send(message)
            .then((response) => {
                console.log('Successfully sent message:', response);
            }).catch((error) => {
                console.log('Error sending message:', error);
            });
        return 0;
    });

当我尝试部署时出现错误:

每个 then() 都应该返回一个值或为字符串 .then((response) => { 抛出 promise/always-return"

【问题讨论】:

  • 在 Stack Overflow 上格式化您的代码时,请多加考虑。使用编辑器中的 {} 按钮来格式化代码部分。 Markdown 并没有真正按照您的预期工作。

标签: javascript node.js firebase firebase-cloud-messaging google-cloud-functions


【解决方案1】:

改变这个:

admin.messaging().send(message)
.then((response) => {
  console.log('Successfully sent message:', response);
}).catch((error) => {
  console.log('Error sending message:', error);
  });
 return 0;
 });

进入这个:

return admin.messaging().send(message)
.then((response) => {
 console.log('Successfully sent message:', response);
 return null;
}).catch((error) => {
 console.log('Error sending message:', error);
  });
});

您需要正确终止函数,这样可以避免函数运行时间过长或无限循环产生过多费用。

您可以使用以下方式终止您的函数:

通过返回 JavaScript 承诺来解析执行异步处理的函数(也称为“后台函数”)。

使用res.redirect()res.send()res.end() 终止HTTP 函数。

使用return; 语句终止同步函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    相关资源
    最近更新 更多