Firebase 对错误出现的原因感到困惑
我遵循了本教程,并对代码进行了一些修改,以适合我的项目Firebase 对错误出现的原因感到困惑,firebase,firebase-realtime-database,firebase-cloud-messaging,google-cloud-functions,Firebase,Firebase Realtime Database,Firebase Cloud Messaging,Google Cloud Functions,我遵循了本教程,并对代码进行了一些修改,以适合我的项目 const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.sendNotif = functions.database().ref("/admin/announcement_record").onCre
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotif = functions.database().ref("/admin/announcement_record").onCreate(event =>{
const snapshot = event.data;
// Notification details.
const text = snapshot.val().text;
const payload = {
notification: {
title: "New Announcement",
body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : ''
}
};
// Get the list of device tokens.
return admin.database().ref("/admin/fcmtokens").once('value').then(allTokens => {
if (allTokens.val()) {
// Listing all tokens.
const tokens = Object.keys(allTokens.val());
// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
// Cleanup the tokens who are not registered anymore.
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
tokensToRemove.push(allTokens.ref.child(tokens[index]).remove());
}
}
});
return Promise.all(tokensToRemove);
});
}
});
});
当我尝试部署它时,我得到了这个
28:79警告预期返回箭头末尾的值
函数一致性返回
29:3每个错误然后应返回一个值或抛出承诺/始终返回
34:12警告避免嵌套承诺承诺/不嵌套
正在寻找有关如何修复或修复的建议,以继续本教程。我将对此稍作调整,但大致上,每个错误[:]都应该返回一个值或抛出,这可能是阻止您继续前进的原因。在您的承诺中,您需要始终从每个分支返回承诺或抛出错误- 因此,您需要在if语句的外部添加某种类型的返回,如下所示:
return admin.database().ref("/admin/fcmtokens").once('value').then(allTokens => {
if (allTokens.val()) {
// Listing all tokens.
const tokens = Object.keys(allTokens.val());
// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
// [...snip...]
return Promise.all(tokensToRemove);
});
}
return null; // explicitly return `null`.
// ^^^^^^
});
});
这将帮助您克服lint错误,继续前进。我认为第一个警告与这个错误有关。要修复第二个警告,您必须进行更多的重新组织,但我认为这不是继续前进的必要条件。可能会帮助您检查它,但不确定如何应用它,因为它说不要使用Promise构造函数,这里也是如此。除非我错过了一些东西。谢谢,我不知道该怎么办,我会继续努力推动notif工作。再次感谢。