我正在关注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").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错误每个then()应返回一个值或抛出promise / always-return
34:12警告避免嵌套承诺承诺/不嵌套
寻找有关如何修复或修复以继续本教程的建议。
答案 0 :(得分:1)
我要稍微减少一点,但粗略地说,error[:] Each then() should return a value or throw
可能是阻止你前进的东西。在您的承诺中,您需要始终返回承诺或从每个分支发出错误 - here's a little documentation and examples。
因此,您需要在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错误并继续前进。第一个警告与此错误有关(我认为)。要修复第二个警告,你必须做一些重组,但我认为没有必要继续前进。