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

如何解决Node.js中SyntaxError: await is only valid in async function报错

问题根因及修复方案
  • 语法报错直接原因:提供的UserController.js代码存在语法结构错误,内部异步adduser函数收尾大括号缺失、末尾多了多余的闭合符}),代码块结构断裂导致JS引擎无法正确识别外层的async函数声明,因此抛出await is only valid in async function错误。
  • 代码逻辑错误:SchoolController.js的checkSchool方法逻辑倒置,当School.findOne查询到匹配数据时调用reject,查询不到数据时反而尝试读取空值的cityId属性,会触发空指针报错。
  • 冗余写法问题:async函数本身默认返回Promise,无需额外嵌套Promise包装,也不需要给Promise的executor函数添加async声明。

修复后代码

SchoolController.js

exports.checkSchool = async function (formdata) {
  const finder = { _id: formdata.school_id, is_deleted: false, is_blocked: false }
  // 直接使用mongoose内置Promise调用,无需自行封装
  const schoolRes = await School.findOne(finder);
  if (schoolRes) {
    return { status: true, cityId: schoolRes.cityId };
  } else {
    throw { status: 404, message: "School not found" };
  }
}

UserController.js

exports.adduser = async function (req, pic, type, res) {
  // 提前初始化返回结果,避免未定义报错
  const result = { success: true };
  try {
    const data = await adduser(req, pic, type);
    result.data = data;
    res(result);
  } catch (err) {
    result.success = false;
    if (err.status != undefined) {
      result.status = err.status;
      result.message = err.message;
    } else {
      result.status = 500;
      result.message = "Server Error " + String(err);
    }
    res(result);
  }
};

async function adduser(req, pic, type) {
  const resp = await schoolController.checkSchool(req.body);
  // 后续业务逻辑在此补充即可
  // ..................
}

低版本mongoose需额外添加配置开启Promise支持:mongoose.Promise = global.Promise

内容的提问来源于stack exchange,提问作者Navneesh Saini

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 12:45:04