为什么不尝试捕获块捕获诺言例外?

发布于 2025-02-08 17:55:15 字数 345 浏览 1 评论 0 原文

我对诺言的错误处理感到困惑。答案可能很明显,但我没有得到。

我有以下示例代码:

var test = async function(){
  throw new Error('Just another error')
}

try {
  test().then()
}
catch(err){
  alert('error: ' + err.toString())
}

在我的浏览器中,我在控制台中没有获得警报和未访问(Promise)错误。这是为什么? try..catch块不应该处理错误吗?

I'm confused about error handling with promises. The answer might be obvious, but I'm not getting it.

I have the following example code:

var test = async function(){
  throw new Error('Just another error')
}

try {
  test().then()
}
catch(err){
  alert('error: ' + err.toString())
}

In my browser I don't get an alert and Uncaught (in promise) Error in the console. Why is that? Shouldn't the try..catch block handle the error?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不及他 2025-02-15 17:55:15

我可以看到您的问题的两个可能方面:

  1. test test> test> test test 的一部分中列出的错误。为什么是承诺拒绝而不是同步例外?

  2. test()的承诺被拒绝,为什么 catch> catch 捕获该拒绝?

#1-为什么是拒绝?

因为即使 async 函数在其工作的同步部分中投掷,它也只会拒绝其返回的承诺,它也不会引起同步错误。这只是 async 函数的设计期间做出的设计决定,而智能的一个  - 如果在函数的同步部分投掷时,则是同步错误,但此后将是一个承诺拒绝,它将混乱,难以理解。因此,这很简单:投入 async 函数总是拒绝其承诺。

(这与Promise构造师如何对待执行者回调您传递给它。承诺构造函数同步呼叫您的函数,但是如果您在通话过程中投掷,它会使用您丢弃的东西来拒绝承诺,而不是允许其继续作为同步例外。)

#2-为什么不被> 捕获的拒绝。捕获块?

因为您不使用等待。承诺拒绝只是当您等待的诺言时,拒绝是例外。如果您使用Promise方法,则/ catch /最后将拒绝通过调用拒绝处理程序来处理拒绝,而不是例外机制。

因此,要么使用承诺方法附加履行和拒绝处理程序:

test()
.then(result => {
    // ...use `result` here...
})
.catch(error => {
    // ...handle/report error here...
});

或在 ardync 函数中使用等待(如果您具有顶级 >在您的环境中等待):

// In an `async` function (or the top level of a module in cutting-edge environments)
try {
    const result = await test();
    // ...use `result` here...
}
catch(err){
    // ...handle/report error here...
}

I can see two possible aspects to your question:

  1. The error being thrown in test is in the synchronous (not asynchronous) part of test. Why is it a promise rejection rather than a synchronous exception?

  2. The promise from test() is being rejected, why doesn't catch catch that rejection?

#1 - Why is it a rejection?

Because even if an async function throws during the synchronous portion of its work, that just rejects the promise it returns, it doesn't raise a synchronous error. It's just a design decision made during the design of async functions, and a smart one — if it were a synchronous error when throwing in the synchronous part of the function but a promise rejection after that, it would be chaotic and hard to understand. So it's simple: throwing in an async function always rejects its promise.

(This is consistent with how the promise constructor treats the executor callback you pass into it. When you do new Promise((resolve, reject) => /*...*/}), the promise constructor calls your function synchronously, but if you throw during the call, it uses what you throw to reject the promise rather than allowing it to continue as a synchronous exception.)

#2 - Why isn't rejection caught by the catch block?

Because you're not using await. Promise rejections are only exceptions when you are awaiting the promise. If you use the promise methods then/catch/finally to attach handlers, rejection is handled by calling the rejection handler, not by the exception mechanism.

So either use promise methods to attach fulfillment and rejection handlers:

test()
.then(result => {
    // ...use `result` here...
})
.catch(error => {
    // ...handle/report error here...
});

Or use await in an async function (or at the top level of a module if you have top-level await in your enviroment):

// In an `async` function (or the top level of a module in cutting-edge environments)
try {
    const result = await test();
    // ...use `result` here...
}
catch(err){
    // ...handle/report error here...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文