Node.js中Firebase Messaging部署报错:Each then()需返回值或抛出异常
解决Firebase云函数部署报错:
Each then() should return a value or throw promise/always-return 这个错误是ESLint的promise/always-return规则在提醒你:每个Promise的then回调都必须返回一个值(或者抛出错误),同时Firebase云函数要求你返回一个Promise来告知运行时异步操作何时完成——你的代码里刚好两个问题都存在。
让我们一步步修正:
错误原因分析
- 你的函数最后返回了
0,这是一个同步值,但admin.messaging().send()是异步操作,Cloud Functions会在这个异步操作完成前就终止函数,可能导致推送发送失败或者日志不完整。 then回调里没有返回任何值,违反了ESLint的promise/always-return规则,该规则要求Promise链中的每个环节都要明确返回值或抛出错误,保证Promise链的完整性。
修正后的代码(Promise链式调用版本)
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.createRequest = functions.firestore .document('Requests/{RequestsId}') .onCreate((snap, context) => { console.log('We have a new request'); // 将message定义移到回调内部,确保每次触发都是独立的实例(虽然这里内容固定,但更规范) const message = { notification: { title: 'title!', body: 'body' }, topic: "all" }; // 返回send方法的Promise,让Cloud Functions等待异步操作完成 return admin.messaging().send(message) .then((response) => { console.log('Successfully sent message:', response); // 返回响应值,满足always-return规则 return response; }) .catch((error) => { console.log('Error sending message:', error); // 抛出错误,让Cloud Functions记录失败状态 throw error; }); });
更简洁的async/await版本(推荐)
async/await语法让异步代码更易读,同时天然满足Promise返回的要求:
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.createRequest = functions.firestore .document('Requests/{RequestsId}') .onCreate(async (snap, context) => { console.log('We have a new request'); const message = { notification: { title: 'title!', body: 'body' }, topic: "all" }; try { const response = await admin.messaging().send(message); console.log('Successfully sent message:', response); return response; } catch (error) { console.log('Error sending message:', error); // 抛出错误,告知Cloud Functions操作失败 throw error; } });
关键修改点
- 返回Promise:将
admin.messaging().send()的Promise作为函数返回值,确保Cloud Functions等待推送发送完成后再结束函数。 - 满足ESLint规则:在
then中返回响应值,或在async/await的try块中返回值;catch块中抛出错误,保证Promise链的完整性。 - 代码规范:将
message移到回调内部,避免全局变量可能带来的意外问题。
内容的提问来源于stack exchange,提问作者Алексей Осадчий
相关产品推荐
相关产品推荐

