You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署Firebase函数时遇promise/always-return ESLint错误求助

解决Firebase Functions部署时的promise/always-return错误

嘿,这个错误是ESLint的promise/always-return规则在提醒你:你的Promise链里有then()回调没有返回值或者抛出错误,这会导致Promise链无法正确跟踪异步操作的完成状态,也可能让Firebase Functions无法判断函数何时执行完毕。

从你给出的代码片段来看,大概率是在onWrite的回调里,你发起了异步操作(比如读取Firestore文档),但没有返回顶层的Promise,或者then()内部的异步操作也没返回对应的Promise。

修复步骤和示例代码

下面是补全并修复后的完整代码,我会标注关键的修复点:

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

exports.sendNotification = functions.firestore.document("BecomeProfessional/{user_id}/Notification/{notification_id}")
  .onWrite(event => {
    const user_id = event.params.user_id;
    const notification_id = event.params.notification_id;

    // 1. 必须返回顶层的Promise,告诉Firebase Functions何时完成
    return admin.firestore().collection("Users").doc(user_id).get()
      .then(doc => {
        if (!doc.exists) {
          // 如果文档不存在,抛出错误终止链
          throw new Error(`User ${user_id} not found`);
        }
        
        const token = doc.data().token;
        const payload = {
          notification: {
            title: "新通知",
            body: "你有一条新的专业申请通知",
            sound: "default"
          }
        };

        // 2. 在then()里返回异步操作的Promise,满足ESLint规则
        return admin.messaging().sendToDevice(token, payload);
      })
      .then(response => {
        console.log(`通知发送成功: ${response}`);
        // 3. 即使没有后续操作,也返回一个值(比如true)来满足规则
        return true;
      })
      .catch(err => {
        console.error(`通知发送失败: ${err}`);
        // 4. catch块要么抛出错误,要么返回值,这里抛出让Firebase记录错误
        throw err;
      });
  });

核心修复点解释

  • 返回顶层Promise:Firebase Functions依赖返回的Promise来确定函数执行的开始和结束,漏掉最外层的return会导致函数提前结束,还触发ESLint错误。
  • 每个then()都返回值:不管是异步操作的Promise,还是一个简单的同步值,都要确保then()回调有返回,这样ESLint才会认为Promise链是完整的。
  • 正确处理错误:catch块里要么抛出错误(让Firebase标记函数执行失败),要么返回一个值,不要让catch成为无返回的函数。

这样修改后,你的代码就能通过ESLint检查,顺利部署啦!

内容的提问来源于stack exchange,提问作者SEJAL GAUSWAMI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:15:49