typescript promise rejecting and vscode debugger behavior

浪尽此生 提交于 2019-12-12 14:29:39

问题


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

Here is an examples:

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

,and:

//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.

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?


回答1:


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).

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;
});

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.



来源:https://stackoverflow.com/questions/39063281/typescript-promise-rejecting-and-vscode-debugger-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!