我正在尝试使用 firebase 函数进行通知,但我的 index.js 文件有问题。我需要一点帮助来解决这个问题。我怎样才能避免嵌套 promise 和返回错误?谢谢。
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
最佳答案
尝试返回 sendToDevice
返回的 promise ,而不是像回调一样嵌套它,这样它就可以在外部而不是内部链接。它还希望您从每个 then
中显式返回一个值,因此您可以从最后一个返回
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;
});
关于javascript promise 不会嵌套并返回使用 firebase 云函数的通知错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50556270/