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

Node.js代码添加async后仍提示await仅可在async函数中使用如何解决

问题原因

你遇到的报错是因为await关键字的作用域不正确:

  • 你确实给外层的imageKit函数加了async关键字,但你使用await的位置是在perArray.forEach((item) => { ... })的回调函数里,这个回调函数本身没有加async声明,不属于外层async函数的直接作用域,所以运行时会抛出"await仅可在async函数中使用"的错误。
  • 另外你这里用map却没有接收返回值,属于不必要的调用,直接遍历values即可。

修正方案

推荐改用for...of循环遍历文件,既可以避免异步回调作用域问题,也能方便控制异步操作的执行顺序:

const axios = require("axios");
const FormData = require("form-data");
const imageKit = async (req, res, next) => {
  if (req.files) {
    try {
      const files = req.files;
      const values = Object.values(files);
      // 遍历外层文件数组
      for (const perArray of values) {
        // 遍历单组文件项
        for (const item of perArray) {
          if (item.mimetype === "image/jpeg" || item.mimetype === "image/png") {
            const newForm = FormData();
            const encodedFile = item.buffer.toString("base64");
            newForm.append("file", encodedFile);
            newForm.append("fileName", item.originalname);
            const encodedKey = Buffer.from(
              process.env.IMAGE_KIT + ":"
            ).toString("base64");
            // 此时await处于外层async函数的直接作用域,可正常使用
            const result = await axios({
              method: "POST",
              url: "https://upload.imagekit.io/api/v1/files/upload",
              data: newForm,
              headers: {
                ...newForm.getHeaders(),
                Authorization: `Basic ${encodedKey}`,
              },
            });
            // 可在这里补充上传结果的处理逻辑,比如把返回的资源地址挂载到req对象上传递给后续中间件
          }
        }
      }
      next();
    } catch (error) {
      // 错误传递给全局错误处理中间件,不要留空catch块吞掉报错
      next(error);
    }
  } else {
    // 无上传文件时直接放行
    next();
  }
};

额外注意事项

如果你需要并行上传所有图片提升效率,可以把所有上传请求收集为Promise数组,用Promise.all统一等待执行完成,性能会比串行的for...of更好。

内容的提问来源于stack exchange,提问作者rheina tamara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:27:05