简体   繁体   English

在等待异步函数时,是否需要显式捕获并重新抛出异常?

[英]Do I need to explicitly catch and re-throw exceptions when awaiting an asynchronous function?

If I have 如果我有

async function bar() {
  throw 'bar';
}

What's the difference between 有什么区别

async function foo() {
  await bar();
}

and

async function foo() {
  try {
    await bar();
  } catch(e) {
    throw e;
  }
}

I heard that I need to explicitly catch and re-throw exceptions inside asynchronous functions, but I assumed catch(e) { throw e; } 我听说我需要在异步函数中显式捕获并重新抛出异常,但我假设catch(e) { throw e; } catch(e) { throw e; } is redundant (if there's no extra processing or logging done before the exception is thrown again). catch(e) { throw e; }是多余的(如果没有额外的处理或异常被抛出再次之前记录完成)。 I believe that's how it is in some other languages; 我相信它在某些其他语言中是如何形成的; what about JavaScript? 那JavaScript怎么样?

You do not have to catch and rethrow. 你不必抓住并重新抛出。 If the expression is a promise that rejects, the expression will throw the value of the rejection. 如果表达式是拒绝的承诺,则表达式将抛出拒绝的值。

Source 资源

暂无
暂无

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

相关问题 UnhandledPromiseRejectionWarning 当从内部捕获重新抛出错误到外部捕获 - UnhandledPromiseRejectionWarning when re-throw error from inner catch to outer catch 如何在axios catch()块中重新引发捕获的错误 - How to re-throw the catched error in axios catch() block Svelte / Vanilla JS - 我是否需要在等待异步 function 时使用.then()? - Svelte / Vanilla JS - do I need to use .then() on awaiting an async function? 我是否需要使用 firebase 函数 api 将 throw 放入 try catch 块中才能捕获它? - Do I need to put the throw inside the try catch block for it to be caught, using firebase function api? 如何在没有承诺的情况下从 function 捕获异步错误? - How do I catch an asynchronous error from a function without promises? 需要使用带有try,catch和throw异常的javascript。 我想用它来检查文本框以确保它是数字而不是字母 - Need to use javascript with try,catch and throw exceptions. I want to use it to check a textbox to make sure it is a number not a letter 我是否需要让这个 function 异步等待过滤方法? - Do i need to make this function asynchronous to wait for the filter method? 我需要创建一个模拟/存根来测试该异步功能吗? - Do I need to create a mock/stub to test this asynchronous function? 在等待异步 function 后运行同步调用 - Running a synchronous call after awaiting an asynchronous function 等待异步函数阻塞主线程 - Awaiting asynchronous function blocks main thread
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM