部署Firebase云函数时出现unexpected token doc错误排查
报错原因与修正方案
- 直接触发
unexpected token doc报错的语法问题:JavaScript规范要求if判断的条件表达式必须包裹在圆括号内,代码中if doc.data().notify未添加左括号,解析器识别到后续的doc标识符时就会抛出该语法错误,修改为if (doc.data().notify)即可消除当前部署报错。 - 未补全异步await的问题:
tokenRef.collection('members').get()是返回Promise的异步方法,原代码未添加await,获取到的并非实际的查询快照对象,后续调用forEach方法会直接触发类型错误,需修正为const tokenSnapshot = await tokenRef.get()。 - 异步语法兼容问题:forEach的普通回调不支持直接使用await语法,原代码在forEach回调内写await会触发上下文语法错误,替换为
for...of循环遍历查询结果即可兼容异步逻辑。 - 代码规范遗漏:
const parentName = parentDoc.data().name行末缺失分号,虽然依赖JS自动分号插入机制不会直接报错,仍建议补全保持代码规范。
修正后的可直接部署的完整代码:
const admin = require('firebase-admin'); admin.initializeApp(); exports.sendRoomNotification = functions.firestore.document('/Rooms/{room}/messages/{message}').onCreate(async (snap, context) => { // 获取新消息发送者ID const childDoc = await snap.ref.get(); const childUsername = childDoc.data().senderId; // 获取房间名称 const roomRef = snap.ref.parent.parent; const parentDoc = await roomRef.get(); const parentName = parentDoc.data().name; console.log('parent.name => ', parentName); // 查询房间成员列表 const tokenRef = roomRef.collection('members'); const tokenSnapshot = await tokenRef.get(); // 遍历成员发送推送通知 for (const doc of tokenSnapshot.docs) { if (doc.data().notify) { const message = { notification: { title: 'Prizm', body: `@${childUsername} send a message in ${parentName}`, badge: '1', sound: 'default' }, token: doc.data().fcmToken } const response = await admin.messaging().send(message); console.log(response); } } })
内容的提问来源于stack exchange,提问作者seth.eeee
相关产品推荐
相关产品推荐

