Firebase Functions部署报错:Promise相关问题及代码修复请求
解决Firebase Functions部署时的Promise Lint错误
嘿,我来帮你搞定这个Firebase Functions的部署问题!先看看你遇到的两个lint错误,还有代码里的几个小拼写问题,咱们一个个解决:
先修正基础语法错误
你的代码里有几个明显的拼写和API使用错误,这也是导致后续问题的诱因:
- 你使用的是
onWrite触发器,参数是change和context,但代码里写了event.data——这是旧版本Firebase Functions的写法,应该换成change.after来获取更新后的数据;另外vall()是拼写错误,正确的方法是val()。 - 数据库路径里的参数是
{notification_id},但你代码里定义的是const notification = context.params.notification;,应该改成const notification_id = context.params.notification_id;才能正确获取到对应的参数值。
解决Promise相关的Lint错误
你的终端报错里的两个问题都是ESLint的Promise规则触发的,咱们逐一修复:
1. 修复promise/no-nesting(避免嵌套Promise)
原来的代码在deviceToken.then()的回调里又嵌套了admin.messaging().sendToDevice().then(),这种嵌套写法会让代码可读性变差,也违反了ESLint的规则。我们可以把它改成链式调用,让Promise链扁平化。
2. 修复promise/always-return(每个then()必须返回值或抛出错误)
最后一个then块里只有console.log语句,没有返回任何值,这违反了ESLint的always-return规则。我们需要在这里返回一个值,比如返回一个resolved状态的Promise,或者直接返回操作的结果。
修复后的完整代码
'use strict'; 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) => { const user_id = context.params.user_id; const notification_id = context.params.notification_id; // 修正参数名 console.log('The User Id is : ', user_id); // 修正API写法和拼写错误 if (!change.after.val()) { console.log('A notification has been deleted from the database : ', notification_id); return Promise.resolve(); // 这里返回一个resolved Promise,避免无返回值 } // 链式调用Promise,避免嵌套 return admin.database().ref(`/Users/${user_id}/device_token`).once('value') .then(result => { const token_id = result.val(); const payload = { notification: { title: "Friend Request", body: "You have received a new Friend Request", icon: "default" } }; // 返回messaging的Promise,继续链式调用 return admin.messaging().sendToDevice(token_id, payload); }) .then(response => { console.log("This was the notification Feature"); // 返回一个值,满足always-return规则 return Promise.resolve("Notification sent successfully"); }) .catch(error => { // 别忘了捕获错误,避免未处理的Promise rejection console.error('Error sending notification:', error); return Promise.reject(error); }); });
修复说明
- 把嵌套的Promise改成链式调用,解决了
promise/no-nesting的警告。 - 每个
then块都返回了对应的Promise或者resolved值,解决了promise/always-return的错误。 - 修正了API拼写和参数名错误,确保触发器逻辑正确。
- 添加了
catch块来捕获可能的错误,避免未处理的Promise rejection问题。
内容的提问来源于stack exchange,提问作者Ahmed Amine
相关产品推荐
相关产品推荐

