При развертывании облачной функции Firebase выдается сообщение об ошибке «Каждый из них должен вернуть значение или выбросить» - PullRequest
0 голосов
/ 22 сентября 2019

Я новичок в облачных функциях, поэтому у меня возникли проблемы с приведенным ниже кодом, ошибка в последней части, где упоминается console.log, пожалуйста, помогите, что я должен был сделать для успешного развертывания функции, так как я следую заВ учебнике нет такой ошибки для имени.

'use-strict'

const functions = require('firebase-functions');
const admin = require("firebase-admin");

admin.initializeApp(functions.config().firebase);
exports.sendNotifications = functions.firestore.document("users/{user_id}/notifications/{notification_id}").onWrite(event => {


    const user_id = event.params.user_id;
    const notification_id = event.params.notification_id;




    return admin.firestore().collection("users").doc(user_id).collection("notifications").doc(notification_id).get().then(queryResult => {

        const from_user_id = queryResult.data().from;
        const message =  queryResult.data().message;

        const from_data = admin.firestore().collection("users").doc(from_user_id).get();
        const to_data = admin.firestore().collection("user").doc(user_id).get();

        return Promise.all([from_data, to_data]).then(result => {
            const from_name = result[0].data().name;
            const to_name = result[1].data().name;
            const token_id  = result[1].data().token_id;

            const payload  = {
                notification: {
                    title: "Notification from:" + from_name,
                    body: message,
                    icon: "default"


                }
            };

            return admin.messaging().sendToDevice(token_id, payload).then(result =>{

                console.log("notifcation sent");
            });

        });

    });




});

1 Ответ

1 голос
/ 22 сентября 2019

Приковав свои Обещания в цепочку и вернув null в последнем then(), вы должны решить свою проблему следующим образом:

exports.sendNotifications = functions.firestore.document("users/{user_id}/notifications/{notification_id}").onWrite(event => {

    const user_id = event.params.user_id;
    const notification_id = event.params.notification_id;

    return admin.firestore().collection("users").doc(user_id).collection("notifications").doc(notification_id).get()
        .then(queryResult => {

            const from_user_id = queryResult.data().from;
            const message = queryResult.data().message;

            const from_data = admin.firestore().collection("users").doc(from_user_id).get();
            const to_data = admin.firestore().collection("user").doc(user_id).get();

            return Promise.all([from_data, to_data]);
        })
        .then(result => {
            const from_name = result[0].data().name;
            const to_name = result[1].data().name;
            const token_id = result[1].data().token_id;

            const payload = {
                notification: {
                    title: "Notification from:" + from_name,
                    body: message,
                    icon: "default"

                }
            };

            return admin.messaging().sendToDevice(token_id, payload)

        })
        .then(messagingResponse => {
            console.log("notification sent");
            return null;   //Note the return null here, watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/
        });

});

Вы можете взглянуть на соответствующую документацию MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#Chaining

Также обратите внимание, что в вашем коде кажется, что вы не используете константу to_name.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...