代码之家  ›  专栏  ›  技术社区  ›  Antha On Twitch

“1秒内未处理拒绝的承诺”vscode扩展API

  •  5
  • Antha On Twitch  · 技术社区  · 6 年前

    我正在尝试为VS代码编写一个简单的扩展,将选择重命名为给定字符串。应用程序已使用扩展生成器引导: https://code.visualstudio.com/docs/extensions/example-hello-world#_generate-a-new-extension

    为此,我使用以下代码:

    const editor = vscode.window.activeTextEditor;
        if (!editor) throw Error;
    
        const position = editor.selection.active
        const uri = editor.document.uri
    
        vscode.commands.executeCommand("vscode.executeDocumentRenameProvider", uri, position, "donkey")
            .then(edit => {
                if (!edit) throw Error;
    
                return vscode.workspace.applyEdit(edit);
            });
    

    该命令已绑定到keybinding。我使用F5启动调试器(启动vs代码实例以进行调试,如教程中所示: https://code.visualstudio.com/docs/extensions/example-hello-world#_debugging-your-extension )。然后,我在调试实例中打开的文件中选择一组代码,然后按我的键绑定。

    然而,在调试控制台中,我得到了“1秒内未处理的拒绝承诺”。不会引发任何错误,因为executeCommand是一个Thenable,而不是一个真正的承诺,所以我不能对其调用catch()。

    我试图将呼叫包装在try/catch块中,但没有成功。 当我尝试其他事情时,比如用vscode显示消息。窗showInformationMessage或提示用户输入它的工作原理,我没有看到错误。

    我还尝试对扩展的Typescript版本执行同样的操作,但我得到了相同的行为。

    我看不出我做错了什么,是不是我遗漏了什么?

    1 回复  |  直到 6 年前
        1
  •  5
  •   Matt Bierner    6 年前

    Thenable.then 接受两个参数:成功延续和失败延续。您可以使用故障延续来确保正确处理拒绝:

    vscode.commands.executeCommand("vscode.executeDocumentRenameProvider", uri, position, "donkey")
        .then(edit => {
            if (!edit) throw Error;
    
            return vscode.workspace.applyEdit(edit);
        })
        .then(undefined, err => {
           console.error('I am error');
        })
    

    这样,如果 executeCommand ,上一个 then applyEdit 失败,拒绝被正确处理