如何让for循环等待异步函数完成异步操作后再执行下一次调用
解决“Code is already running!”错误的方案
你的问题出在for循环里直接调用runCode(i)却没有等待异步任务完成,导致所有code-runner.run命令几乎同时触发,而该API不允许同时运行多个任务,因此报错。
只需在循环调用runCode时添加await,让每个任务执行完成后再启动下一个即可,两种修改方式如下:
方式一:使用for...of循环(更直观)
const getAllFiles = vscode.workspace.findFiles('**/*.*', '**/node_modules/**'); const onActivation = async () => { const allFiles = await getAllFiles const runCode = async (file) => { await vscode.window.showTextDocument(file) await vscode.commands.executeCommand('code-runner.run', null) } // 逐个处理文件,等待当前任务完成再执行下一个 for (const file of allFiles) { await runCode(file) } } onActivation()
方式二:保留原索引循环,添加await
const getAllFiles = vscode.workspace.findFiles('**/*.*', '**/node_modules/**'); const onActivation = async () => { const allFiles = await getAllFiles const runCode = async (i) => { await vscode.window.showTextDocument(allFiles[i]) await vscode.commands.executeCommand('code-runner.run', null) } // 等待当前runCode的异步操作全部完成,再进入下一次循环 for (let i = 0; i < allFiles.length; i++) { await runCode(i) } } onActivation()
核心逻辑是通过await阻塞循环,确保前一个文件的打开和代码运行操作全部完成后,才会处理下一个文件,避免同时触发多个code-runner.run请求。
内容的提问来源于stack exchange,提问作者Ethan
相关产品推荐
相关产品推荐

