typescript - 以编程方式调用组织导入并随后保存文件

标签 typescript visual-studio-code plugins async-await vscode-extensions

我在做什么基本上是:

async function doItAll(ownEdits: Array<TextEdit>) {
    const editor: TextEditor = await getEditor();
    applyOwnChanges(editor, ownEdits);
    await commands.executeCommand('editor.action.organizeImports',
        editor.document.uri.path);
    await editor.document.save();
}

一切正常,但 save发生在 organizeImports 之前完成,当导入被修改时,我最终得到一个肮脏的编辑器。

我检查了一下我没有忘记 await关键字,但它的工作原理就像它不存在一样。

这可能是一个错误,或者我可能正在做或期待一些错误的事情。我是吗?

最佳答案

事实上,在它实际更新文档之前,组织导入命令返回。

作为解决方法使用 onDidChangeTextDocument 当组织导入完成并且您的文档准备好保存时进行拦截。

const handler = vscode.workspace.onDidChangeTextDocument(doc => {
  if (doc.document.uri.path === editor.document.uri.path) {
    doc.document.save()
    handler.dispose()
  }
})

关于typescript - 以编程方式调用组织导入并随后保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62244964/

相关文章:

javascript - tsconfig 中的模块选项是用来做什么的?

typescript - 如何在 TypeScript 中同步运行 Promise?

amazon-web-services - 类型不正确。在 vscode 中编辑时,cloudformation yml 文件中应有 "string"

visual-studio-code - 有没有办法从 VS Code 中的扩展程序打开工作区?

java - Java库插件是否完全涵盖Java插件功能?

php - 使用 ACF 从分类术语中获取图像

ios - Xamarin.Forms Xam.Plugin.Media 在 iOS 上拍照

javascript - angular4 - 异步数据加载 - async ngFor 循环?

c# - 错误: "the application completed without reading the entire request body" Angular/C#

visual-studio-code - 如何在一个 vscode 工作区中定义/引用多个tasks.json 文件?