【问题标题】:Firebase cloud functions says Unreachable and each then() should return a value or throw promise/always-returnFirebase 云函数说 Unreachable 并且每个 then() 应该返回一个值或抛出 promise/always-return
【发布时间】:2018-09-25 06:12:56
【问题描述】:

Firebase 云函数的 Javascript 代码给出了为推送通知编写的错误

index.js

'use strict'
//Install functions and admin sdks'
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((change, context) => {
    //onwrite will run if data changed
    const user_id = context.params.user_id;
    const notification = context.params.notification;

    if (context.params === null) {
        return console.log("Notification Has Been Deleted");
    }
    let token_id = null;
    const deviceToken = admin.database.ref(`/Users/${user_id}/device_token`).once('value');
    return deviceToken.then(result => {

        token_id = result.val();

        const payload = {
            notification:{
                title:"Friend Request",
                body:"You have recieved a new friend request",
                icon:"default"
            }
        };


    });


    return admin.messaging().sendToDevice(token_id, payload).then(response =>{
        console.log('This is the notify feature');
    }).catch(err => {
        console.log('Error getting documents', err);
    });

});

运行 firebase deploy 命令时出现如下错误。如果有人可以支持,我将不胜感激。

错误

error 每个 then() 都应该返回一个值或者抛出 promise/always-return 错误无法访问的代码 no-unreachable error 每个 then() 都应该返回一个值或抛出 promise/always-return

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.      

【问题讨论】:

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


    【解决方案1】:

    错误是说您应该从传递给任何 then() 方法的回调中返回一个值。您的代码中有两个 then() 方法。如果你没有东西要发送到 Promise 链中的下一项工作,只需在函数末尾处 return null 即可。

    不过,您的代码中还有一个更大的问题。您在函数的顶层有两个 return 语句,一个接一个。这几乎肯定会导致另一个错误,或者至少无法达到您的预期。 (您必须只返回一个在所有工作完成后解决的 Promise。)

    【讨论】:

      【解决方案2】:

      道格感谢您的评论。然后我更改了代码。现在它被部署没有任何错误。但是在调用该方法后,它在firebase函数控制台中给出了一个错误。(调用该方法意味着使用android应用添加一个新的通知) 在有效负载中,没有令牌:deviceToken 部分也不起作用

      'use strict'
      
      
      //Install functions and admin sdks'
      const functions = require('firebase-functions');
      const admin =require('firebase-admin');
      var FCM = require('fcm-push');
      admin.initializeApp();
      
      
      var serverKey = 'MY_SERVER_KEY_HERE';
      var fcm = new FCM(serverKey);
      
      
      
      exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
          //onwrite will run if data changed
          const user_id = context.params.user_id;
          const notification = context.params.notification;
      console.log('user : '+user_id)
      console.log('notification : '+notification)
          // If exit the function.
          if (!change.after.val()) {
            return console.log('User ', user_id, 'notification', notification);
          }
      
      // Only edit data when it is first created.
            if (change.before.exists()) {
              return null;
            }
            // Exit when the data is deleted.
            if (!change.after.exists()) {
              return null;
            }
      
          const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
          console.log("Dev TOken : "+deviceToken);
          return admin.database().ref(`/Users/${user_id}/device_token`).once('value').then(result => {
      
      
              const payload = {
                  notification:{
                      title:"Friend Request",
                      body:"You have recieved a new friend request",
                  },
                  tokens:deviceToken
              };
      
              return admin.messaging().send(payload).then(response =>{
                  return console.log('This is the notify feature');
              }).catch(err => {
                  return console.log('Error getting documents', err);
              });
          })
      
      });
      

      输出:- https://i.imgur.com/9PRwMbi.png

      如果有任何错误,谁能更正代码?

      【讨论】:

        【解决方案3】:

        我希望它能正常工作,你应该像这样返回

        return console.log('This is the notify feature');
        

        【讨论】:

          【解决方案4】:

          谢谢大家。我修好了。

          'use strict'
          
          //Install functions and admin sdks'
          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) => {
              //onwrite will run if data changed
              const user_id = context.params.user_id;
              //const from = context.params.from;
              const notification_id = context.params.notification_id;
              console.log('user : '+user_id);
              console.log('notification_id : '+notification_id);
              //console.log('notification : '+notification)
              //console.log('from : '+from)
              // If exit the function.
              if (!change.after.val()) {
                return console.log('Sender ', user_id, 'From', from);
              }
          
          // Only edit data when it is first created.
                if (change.before.exists()) {
                  return null;
                }
                // Exit when the data is deleted.
                if (!change.after.exists()) {
                  return null;
                }
          
              // if (context.params === null) {
              //     return console.log("Notification Has Been Deleted");
              // }
          
          //    let token_id = null;
              const getDeviceTokensPromise = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
          
              return getDeviceTokensPromise.then(result => {
                const payload = {
                  notification: {
                    title: 'You have a new follower!',
                    body: `is now following you.`,
                    icon: 'default'
                  }
                };
          
                return admin.messaging().sendToDevice(result.val(), payload);
          
              }).then(res => {
                return console.log(JSON.stringify(res));
              });  
          
          });
          

          【讨论】:

            【解决方案5】:

            对于云函数,如果它的 https 触发器,那么它必须向用户返回一个响应,如果任何其他类型的触发器它必须返回一个 Promise。只是 return Promise.resolve("Done"); 我试过 return null 但这对我不起作用。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2018-09-11
              • 2019-02-19
              • 2019-06-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-04-02
              相关资源
              最近更新 更多