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

TypeScript中如何确保doAsyncStuff执行完成后再运行doNextStep

问题原因

你的代码核心问题是Array.prototype.forEach不会等待内部的异步函数执行完成:你传入forEach的每个async回调都会独立触发执行,doAsyncStuff函数不会等待这些回调全部执行完毕,就会直接返回true,所以.then会提前触发,最终导致doNextStep在目录遍历还没完成的时候就执行了。

修复方案

把forEach替换为map收集每个异步操作的Promise,再通过Promise.all等待所有异步操作全部完成即可,修复后代码如下:

async function doAsyncStuff() {
    if (vscode.workspace.workspaceFolders) {
        // 收集所有目录读取任务的Promise
        const dirReadTasks = vscode.workspace.workspaceFolders.map(async (e) => {
            for (const [name, type] of await vscode.workspace.fs.readDirectory(e.uri)) {
                console.log(name);
            }
        });
        // 等待所有目录读取任务执行完毕
        await Promise.all(dirReadTasks);
    }
    return true;
}

function doNextStep() {
    console.log('next step');
}
调用方式

你原来的调用逻辑不需要修改就能正常生效:
doAsyncStuff().then(_ => doNextStep());
如果是在async函数内部调用,也可以用await写法:

async function main() {
    await doAsyncStuff();
    doNextStep();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:06:08