Node.js 10中async/await使用问题:Unexpected token db报错如何解决
问题排查与解决
根因分析
你遇到的语法错误核心原因是**await关键字只能在标记了async的函数内部使用**,你定义的setDailyPointStatus函数没有添加async修饰符,JS解析器遇到await时无法识别,就会把后续的db判定为非法意外token抛出错误。
除此之外你的代码还存在两处会导致逻辑异常的问题:
- 调用的
db.collection(...).get()是异步方法,返回值为Promise,你没有添加await就直接判断.empty属性,实际拿到的不是查询快照,永远不会触发你写的判断分支 - 若你的部署环境开启了旧语法校验规则,即使语法正确也可能额外触发解析报错
修复方案
步骤1:给setDailyPointStatus函数添加async修饰符
修改函数定义如下:
async function setDailyPointStatus(point, type){ // 原有代码逻辑保持不变 try { await db.runTransaction(async (t) => { }); console.log('Transaction success!'); } catch (e) { console.log('Transaction failure:', e); } }
步骤2:修复路由方法内的异步调用逻辑
路由的回调函数也需要添加async修饰符,所有异步数据库操作前补充await:
// 回调函数前加async修饰符 router.get('/test', async function(req, res, next) { // 异步get方法前加await const offerwallHistory_snapshot = await db.collection('offerwallHistory').doc(uid).collection('offerwallHistory').where('completedRewardKey', '==', event_id).get(); if (offerwallHistory_snapshot.empty) { // 异步get方法前加await const pointHistory_snapshot = await db.collection('pointHistory').doc(uid).collection('pointHistory').orderBy('pointDate', 'desc').limit(1).get(); if (pointHistory_snapshot.empty) { ... } // 写操作如果需要保证执行顺序可添加await,也可以用Promise.all批量执行提升效率 await db.collection('pointHistory').doc(uid).collection('pointHistory').add(newPointHistory); await db.collection('users').doc(uid).update({point: addTotalPoint}); await db.collection('offerwallHistory').doc(uid).collection('offerwallHistory').add(offerwallHistory_data); await db.collection('adminPointHistory').add(adminPointHistory_data); // 调用async异步函数需要加await,否则会变成后台异步执行,异常无法被上层捕获 await setDailyPointStatus(reward, 12); return res.send(event_id + ":OK").status(200); }else{ return res.send(event_id + "else OK").status(200); } return res.send(":OK").status(200); });
步骤3:兼容Node.js 10环境校验
如果修复上述代码后仍有解析报错,若你的项目使用ESLint做语法校验,可在项目根目录的.eslintrc配置中指定ECMAScript版本为2017及以上:
{ "parserOptions": { "ecmaVersion": 2017 } }
内容的提问来源于stack exchange,提问作者peterbbong
相关产品推荐
相关产品推荐

