为什么不尝试捕获块捕获诺言例外?
我对诺言的错误处理感到困惑。答案可能很明显,但我没有得到。
我有以下示例代码:
var test = async function(){
throw new Error('Just another error')
}
try {
test().then()
}
catch(err){
alert('error: ' + err.toString())
}
在我的浏览器中,我在控制台中没有获得警报和未访问(Promise)错误
。这是为什么? try..catch块不应该处理错误吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可以看到您的问题的两个可能方面:
test
在test> test> test test
的一部分中列出的错误。为什么是承诺拒绝而不是同步例外?test()
的承诺被拒绝,为什么catch> catch
捕获该拒绝?#1-为什么是拒绝?
因为即使
async
函数在其工作的同步部分中投掷,它也只会拒绝其返回的承诺,它也不会引起同步错误。这只是async
函数的设计期间做出的设计决定,而智能的一个  - 如果在函数的同步部分投掷时,则是同步错误,但此后将是一个承诺拒绝,它将混乱,难以理解。因此,这很简单:投入async
函数总是拒绝其承诺。(这与Promise构造师如何对待执行者回调您传递给它。承诺构造函数同步呼叫您的函数,但是如果您在通话过程中投掷,它会使用您丢弃的东西来拒绝承诺,而不是允许其继续作为同步例外。)
#2-为什么不被
>
捕获的拒绝。捕获
块?因为您不使用
等待
。承诺拒绝只是当您等待
的诺言时,拒绝是例外。如果您使用Promise方法,则
/catch
/最后
将拒绝通过调用拒绝处理程序来处理拒绝,而不是例外机制。因此,要么使用承诺方法附加履行和拒绝处理程序:
或在
ardync
函数中使用等待
(如果您具有顶级>在您的环境中等待):
I can see two possible aspects to your question:
The error being thrown in
test
is in the synchronous (not asynchronous) part oftest
. Why is it a promise rejection rather than a synchronous exception?The promise from
test()
is being rejected, why doesn'tcatch
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 ofasync
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 anasync
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 areawait
ing the promise. If you use the promise methodsthen
/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:
Or use
await
in anasync
function (or at the top level of a module if you have top-levelawait
in your enviroment):