【问题标题】:Will errors be caught by try catch block when I don't have await in front of my asynchronous function?当我的异步函数前面没有等待时,try catch 块会捕获错误吗?
【发布时间】:2018-12-28 14:09:54
【问题描述】:

如果我的异步函数前面没有等待,下面的 JavaScript try catch 块是否仍会捕获错误,如下所示?

async () => {
   try {
      someAsynchronouseFunction();
   } catch (err) {
      // will errors from my asynchronous function still be caught here?
   }
}

【问题讨论】:

  • 你测试了吗?发生了什么?我猜不会,因为没有await,你只会调用一个返回promise的函数,错误会传递给任何catch回调而不是调用者。
  • 如果someAsynchronouseFunction 真的是异步的,它只会返回一个未解决的承诺(你甚至不存储),并且代码将继续。然后异步函数可能会在稍后执行,抛出一个错误,并且该错误将无处被捕获。

标签: javascript asynchronous error-handling async-await try-catch


【解决方案1】:

不,他们不会,因为someAsynchronouseFunction(); 只会解析为被拒绝的Promise,而单独被拒绝的Promise 不会导致错误,即使在try 块中也是如此。相反,您只会在控制台中看到Uncaught (in promise) Error: err!

async function someAsynchronouseFunction() {
  await new Promise(res => setTimeout(res, 1000));
  console.log('end of someAsynchronouseFunction, about to throw');
  throw new Error('err!');
}

const foo = async () => {
   try {
      someAsynchronouseFunction();
   } catch (err) {
     console.log('error found: ' + err);
   }
   console.log('end of foo');
}

foo();

【讨论】:

    猜你喜欢
    • 2019-02-11
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    相关资源
    最近更新 更多