简体   繁体   English

无法捕获异步 function 引发的错误

[英]Unable to catch error thrown by Async function

I was readingthis article.我正在读这篇文章。 In the below code the async 'foo' function returns the result of the async 'waitAndMaybeReject' function.在下面的代码中,异步 'foo' function 返回异步 'waitAndMaybeReject' function 的结果。

I am unable to understand why the catch block in 'foo' function is not executed when 'waitAndMaybeReject' throws an error.我无法理解为什么当 'waitAndMaybeReject' 抛出错误时,'foo' function 中的 catch 块没有被执行。

 async function waitAndMaybeReject() { await new Promise(r => setTimeout(r, 5000)); const isHeads = false; //const isHeads = true; if (isHeads) return 'yay'; throw Error('Boo;'); } async function foo() { try { return waitAndMaybeReject(); } catch (e) { return 'caught'; } } foo();

You need to await the waitAndMaybeReject() function in order to be able to catch the exception.您需要await waitAndMaybeReject() function 才能捕获异常。 As it is described in the article you refer to:如您所指的文章中所述:

By returning waitAndMaybeReject(), we're deferring to its result, so our catch block never runs.通过返回 waitAndMaybeReject(),我们推迟了它的结果,所以我们的 catch 块永远不会运行。

To make it simple, when you return waitAndMaybeReject() you don't wait for it to resolve/reject in the try... catch block.为简单起见,当您return waitAndMaybeReject()时,您无需等待它在try... catch块中解析/拒绝。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM