用于firebase的node.js中的messaging()问题

时间:2019-05-19 06:01:07

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

我想组织有关向Firestore添加文档的发送推送通知。我正在使用来自Firebase网站的示例中的代码来编写node.js。

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“

1 个答案:

答案 0 :(得分: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;语句终止同步函数。