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

使用async await时代码未等待执行,读取文件路径得到空数组如何解决

问题原因

await关键字仅能对Promise对象生效,你当前调用的glob是回调风格API,不会返回Promise,因此await无法阻塞代码等待回调执行,gerall函数会提前返回,导致打印allfiles时数组还未被赋值。

修复方案

方案1:手动封装回调为Promise(通用适配方案)

将回调风格的逻辑包装为返回Promise的函数,即可正常使用async/await等待执行完成:

const glob = require("glob");

inicio();

async function inicio() {
    const allfiles = await gerall();
    console.log(allfiles);
}

async function gerall() {
    const getDirectories = function(src) {
        return new Promise((resolve, reject) => {
            glob(src + '/**/*', (err, res) => {
                if (err) return reject(err);
                resolve(res);
            });
        });
    };
    const res = await getDirectories('./');
    // 直接返回过滤后的结果,避免使用全局变量
    return res.filter(element => 
        !element.includes("node_module") &&
        !element.includes("package.json") &&
        !element.includes("package-lock.json") &&
        element.substring(1).includes(".")
    );
}

方案2:使用glob内置的Promise API(更简洁)

新版glob已经内置了Promise风格的调用方法,无需手动封装:

// 旧版glob可替换为 const { glob } = require("glob")
const glob = require("glob/promise");

inicio();

async function inicio() {
    const allfiles = await gerall();
    console.log(allfiles);
}

async function gerall() {
    const res = await glob('./**/*');
    return res.filter(element => 
        !element.includes("node_module") &&
        !element.includes("package.json") &&
        !element.includes("package-lock.json") &&
        element.substring(1).includes(".")
    );
}

内容的提问来源于stack exchange,提问作者luis felipe Caruzo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:06:00