Firebase云功能 - 返回未定义的

时间:2017-10-16 19:14:59

标签: firebase firebase-cloud-messaging google-cloud-functions

这是我用来从我的数据库中获取senderName和messageText的代码。在我的日志中,我收到一条错误消息“函数返回未定义,预期的Promise或value”。我正在使用此功能向消息的接收者发送通知。通知正在正确发送。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


exports.sendPushNotification = functions.database.ref('/messages/{messageId}').onWrite(event => {


var db = admin.database();

var messageText;
var senderName;
var receiverId;
var senderId;

var messageId = event.params.messageId;


var messageTextRef = db.ref('/messages/' + messageId + '/text');
var senderIdRef = db.ref('/messages/' + messageId + '/fromId');
var receiverIdRef = db.ref('/messages/' + messageId + '/toId');

messageTextRef.once("value", function(data) {

        messageText = data.val();

senderIdRef.once("value", function(data) {

        senderId = data.val();


receiverIdRef.once("value", function(data) {

        receiverId = data.val();


 var senderNameRef = db.ref('/users/' + senderId + '/name');

senderNameRef.once("value", function(data) {

        senderName = data.val();

        console.log(senderName);
        console.log(messageText);



const payload = {

    notification : {
        title: String(senderName),
        body: String(messageText),
        badge: "1",
        sound: 'default',
    }

};

     return admin.database().ref('fcmToken').once('value').then(allToken => {
        if (allToken.val()) {
            const token = Object.keys(allToken.val());
        return admin.messaging().sendToTopic(receiverId, payload).then(response => {

            });

         };



        }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
    });


 }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
    });    


     }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
    });



 }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
    });


});                                                                               
});

1 个答案:

答案 0 :(得分:2)

你有一个怪物功能。如果在获得应该解决问题的所有数据库值时返回最外面的Promise,并确保在所有计算完成之前不停止函数。在你的情况下,这是在线~25:

...

return messageTextRef.once("value", function(data) {

...