本文介绍了打字稿承诺拒绝和vscode调试器行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用打字稿来学习Promise,并且在理解导致vscode调试行为的原因时遇到了一些问题。

I'm trying to learn promises, with typescript, and i have some problems, understanding what causes such vscode debugging behavior.

这里是一个示例:

// example 1
new Promise((resolve, reject) => {
    reject("test1"); // debugger stops as on uncaught exception
})
.catch(
    error => {
        console.log(error);
    }
);
// output: "test1"

,并且:

//example 2
new Promise((resolve, reject) => {
    setTimeout(() => {
        reject("test2"); // debugger never stops
    });
})
.catch(
    error => {
        console.log(error);
    }
);
// output: "test2"

如您所见,调试器在以下位置停止答应拒绝,但在其他情况下则不能。但是在所有情况下都捕获了错误,并且没有未处理的异常。

As you can see in one case debugger stops at promise reject, but in other case, not. But in all cases error is catched, and no unhandled exceptions.

是vscode特定行为还是我使用的es6-promise绑定?还是我做错了方法?有没有人遇到过同样的问题?

Is it vscode specific behavior or maybe es6-promise binding that i use? Or i'm doing it incorrect way? Has anyone faced same problem?

推荐答案

这是VSCode挂钩的Chrome调试器使用的一种启发式方法。他们认为,同步拒绝通常是您要打破的程序员错误(例如拼写错误),而异步错误则不是,因为它们通常是IO(读取文件)。

This is a heuristic that the Chrome debugger which VSCode hooks into uses. They assume that synchronous rejections are typically programmer errors you want to break on (like a typo) and asynchronous ones are not since they're typically IO (reading a file).

这是一种非常愚蠢的启发式方法,但在某些情况下通常很有意义。您可以做的一件事是包含用于调试构建的bluebird(如果不将 Promise 子类化,则100%兼容),然后添加未处理的拒绝钩子:

It's a pretty dumb heuristic but it typically makes sense for some cases. One thing you can do is include bluebird for the debug build (it's 100% compliant if you don't subclass Promise) and then add an unhandled rejection hook:

Promise.onPossiblyUnhandledRejection(function(e, promise) {
    throw e;
});

使用更好的启发式方法。您也可以使用本机的Promise(带有拒绝事件)来执行此操作,但是我不知道如何关闭同步引发的自动中断。

Which uses a much nicer heuristic. You can also do this with native promises (with rejection events) but I don't know how you can turn off the automatic breaking on synchronous throws.

这篇关于打字稿承诺拒绝和vscode调试器行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:16