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

调用async函数出现ReferenceError: await未定义的问题求助

解决ReferenceError: await is not defined及异步函数逻辑问题

一、先处理调用时的await错误

ReferenceError: await is not defined的核心原因是**await只能在async函数内部,或者ES模块的顶层作用域中使用**,分两种情况修复:

  1. 在普通函数中调用
    如果你是在非async函数里执行const controllers = await getController();,必须把这段代码包裹到一个async函数中:

    async function init() {
      const controllers = await getController();
      // 后续业务逻辑
    }
    init();
    
  2. 使用顶层await(ES模块模式)
    若想在文件顶层直接用await,需要满足两个条件:

    • 项目配置为ES模块:在package.json中添加"type": "module"
    • tsconfig的compilerOptions中module设置为Node16或NodeNext(你的配置已经满足)

二、修复getController函数的异步逻辑漏洞

你的原函数存在严重问题:回调版的fs.readdir无法被await等待,导致函数会在目录读取、模块导入完成前就返回空数组,同时await对回调函数完全无效。必须改用Promise版本的文件操作API:

修正后的完整代码:

import fs from 'fs/promises';
import path from 'path';

export default async function getController() {
    const directoryPath = path.join(__dirname, '@presentation/controller');
    const controller: any[] = [];

    try {
        // 使用Promise版readdir,await能正确等待目录读取完成
        const files = await fs.readdir(directoryPath);
        
        for (const file of files) {
            const fullPath = path.join(directoryPath, file);
            if (path.extname(fullPath) === '.ts') {
                try {
                    const module = await import(fullPath);
                    controller.push(module.default);
                } catch (err) {
                    console.error('Erro ao importar o módulo:', err);
                }
            }
        }
    } catch (err) {
        console.error('Unable to scan directory:', err);
    }

    return controller;
}

关键修改点:

  • 替换fs.readdir(回调版)为fs.promises.readdir(Promise版),让await能正确等待异步操作完成
  • 把目录读取的错误处理从回调内移到外层try/catch,更符合async/await的代码风格
  • 确保所有异步操作完成后,才返回收集到的控制器数组

三、验证tsconfig配置

你的现有配置基本满足要求,额外确认以下几点:

  • compilerOptions.target设置为es2017或更高(已满足,支持async/await)
  • compilerOptions.moduleResolution设置为Node16(和module: Node16配套,确保模块解析正确)
  • 若使用CommonJS模块,不要用顶层await,必须把调用逻辑放在async函数内

内容的提问来源于stack exchange,提问作者Aurelio Moreira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:17:27