Ошибка в скрипте functions @ lint

Я пытаюсь развернуть Firebase, но получаю эту ошибку

error Each then() should return a value or throw promise/always-return

это мой код

'use strict'

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


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




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

  console.info('We have a notification from : ', user_id);



  if (!event.data.val()){

    return console.info('A Notification has been deleted from the database : ', notification_id);

  }


  const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');

  return fromUser.then(fromUserResult => {

    const from_user_id = fromUserResult.val().from;

    console.info('You have new notification from  : ', from_user_id);


    const userQuery = admin.database().ref(`Users/${from_user_id}/name`).once('value');
    const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');

    return Promise.all([userQuery, deviceToken]).then(result => {

      const userName = result[0].val();
      const token_id = result[1].val();


      const payload = {
        notification: {
          title : "New Friend Request",
          body: `${userName} has sent you request`,
          icon: "default",
          click_action : "in.tvac.akshaye.lapitchat_TARGET_NOTIFICATION"
        },
        data : {
          from_user_id : from_user_id
        }
      };



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

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

      });

    });

  });

});

это журнал ошибок

npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! functions@ lint: eslint . npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the functions@ lint script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\PC\AppData\Roaming\npm-cache_logs\2018-11-09T12_26_46_311Z-debug.log Error: functions predeploy error: Command terminated with non-zero exit code1

попробуйте return null; после console.info('This was the notification Feature');

James Poag 09.11.2018 13:36

@JamesPoag Омг, ты супергерой;) как мне закрыть этот вопрос?

Waseem Ha 09.11.2018 13:39

Я опубликовал очистку, которую провел через ESLint. Обратите внимание, что я связываю then вместо вложенности, и что я добавил catch

James Poag 09.11.2018 13:43

@JamesPoag большое спасибо, проблема решена: D

Waseem Ha 09.11.2018 13:48
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
4
2 307
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Цепочка then вместо вложенности, включает блок catch, всегда возвращается из then.

'use strict'

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

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

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

            console.info('We have a notification from : ', user_id);

            if (!event.data.val())
                return console.info(`A Notification has been deleted from the database : ${notification_id}`);

            return admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value')
                .then(fromUserResult => {

                    const from_user_id = fromUserResult.val().from;

                    console.info(`You have new notification from  : ${from_user_id}`);

                    const userQuery = admin.database().ref(`Users/${from_user_id}/name`).once('value');
                    const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');

                    return Promise.all([userQuery, deviceToken]);
                })
                .then(result => {

                    const userName = result[0].val();
                    const token_id = result[1].val();

                    const payload = {
                        notification: {
                            title: "New Friend Request",
                            body: `${userName} has sent you request`,
                            icon: "default",
                            click_action: "in.tvac.akshaye.lapitchat_TARGET_NOTIFICATION"
                        },
                        data: {
                            from_user_id: from_user_id
                        }
                    };

                    return admin.messaging().sendToDevice(token_id, payload);
                })
                .then(response => {
                    console.info('This was the notification Feature');
                    return null;
                })
                .catch(console.info);
        });

Другие вопросы по теме