Каждый then () должен возвращать значение или выдавать облачные функции Firebase - PullRequest
0 голосов
/ 17 ноября 2018

Я пишу облачную функцию для firebase, используя javascript, но я застрял, я не знаю точного значения ошибки и не могу ее решить .. Состояния ошибки: 27:65 error Каждое then () должно возвращатьЗначение или бросить обещание / всегда возвращать

'use strict'

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

exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {

    const user_id = context.params.user_id;
    const notification_id = context.params.notification_id;
    console.log('We have a notification from : ', user_id);

    if (!change.after.val()) {
        return console.log('A Notification has been deleted from the database : ', notification_id);
    }
    const deviceToken = admin.database().ref(`/ServiceProvider/${user_id}/device_token`).once('value');
    return deviceToken.then(result => {
        const token_id = result.val();
        const payload = {
            notification: {
              title : "New Friend Request",
              body: "You Have Received A new Friend Request",
              icon: "default"
            }
        };

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

            console.log('This was the notification Feature');

        });

    });

});

Ответы [ 3 ]

0 голосов
/ 17 ноября 2018

Это означает, что каждый .then должен содержать возвращаемое значение.Другими словами, избегайте обещания анти-паттерна .

. Вам может показаться, что async функциям легче обернуть голову.Обратите внимание, что вам потребуется запустить Node 8 Runtime для поддержки асинхронного ...

0 голосов
/ 17 ноября 2018

Измените это:

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

        console.log('This was the notification Feature');

    });

На это:

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

        console.log('This was the notification Feature');
        return null;   // add this line

    });

Для обратного вызова then просто необходимо вернуть значение.

Однако, тогда eslint можетпожаловаться на вложенный then() в вашем коде, который также является анти-паттерном.Ваш код на самом деле должен быть структурирован более примерно так:

const deviceToken = admin.database().ref(`/ServiceProvider/${user_id}/device_token`).once('value');
return deviceToken.then(result => {
    // redacted stuff...
    return admin.messaging().sendToDevice(token_id, payload);
}).then(() => {
    console.log('This was the notification Feature');
});

Обратите внимание, что каждый из них затем соединяется друг с другом, а не вкладывается друг в друга.

0 голосов
/ 17 ноября 2018

Измените это:

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

    console.log('This was the notification Feature');

  });

на это:

    return admin.messaging().sendToDevice(token_id, payload).then(response=>{
      console.log('This was the notification Feature');
      return true;
    },err=>
    {
      throw err;
    });

Как говорит ошибка при использовании then, вам необходимо вернуть значение.

...