javascript承诺使用firebase云功能

时间:2018-05-27 20:34:26

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

我正在尝试使用firebase函数进行通知,我的index.js文件存在问题。我需要一些帮助来解决这个问题。如何从嵌套承诺中保存自己并返回错误?谢谢。

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

let firebaseConfig = JSON.parse(process.env.FIREBASE_CONFIG);
exports.sendNotification = functions.database.ref('/Notifications/ {user_id}/{notification_id}').onWrite((change,context) => {

const user_id = context.params.user_id; 
const notification= context.params.notification;

console.log('We have a notification to send to ',user_id);

if(!change.after.val()){

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

}

 const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
        return deviceToken.then(result =>{
                    const token_id = result.val();
                    const payload = {
                        notification: {
                            title : "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");
                });
    });

这是我的错误:

 31:21  warning  Avoid nesting promises                      promise/no-nesting
 31:76  error    Each then() should return a value or throw  promise/always-return

 ✖ 2 problems (1 error, 1 warning)

 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\furkan\AppData\Roaming\npm-cache\_logs\2018-05-27T20_21_53_984Z-debug.log

 Error: functions predeploy error: Command terminated with non-zero exit code1

 Having trouble? Try firebase deploy --help

1 个答案:

答案 0 :(得分:0)

尝试返回 sendToDevice返回的承诺,而不是像回调那样嵌套它,因此它可以链接在外部而不是内部。它还希望您显式返回每个then的值,因此您可以从最后一个值return null或undefined来禁止警告:

return deviceToken.then(result =>{
  const token_id = result.val();
  const payload = {
    notification: {
      title : "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");
  return undefined;
});