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

maa*_*nus 5 plugins async-await typescript visual-studio-code 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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Sha*_*iar 0

executeCommand是 Thenable 。因此,该save()方法应该移到thenable内部。

vscode.commands.executeCommand('editor.action.organizeImports', editor.document.uri.path).then(function(){
        await editor.document.save();
});
Run Code Online (Sandbox Code Playgroud)

如果在完成之前仍然发生保存,organizeImports则尝试调用内部的 save 方法setTimeout(function(){....}, T)

 vscode.commands.executeCommand('editor.action.organizeImports', editor.document.uri.path).then(function(){
       setTimeout(function(){
            await editor.document.save();
       }, 500);
});
Run Code Online (Sandbox Code Playgroud)