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
相关产品推荐
相关产品推荐

