为什么函数 A 不能捕获函数 B 抛出的错误

Why can't function A catch the error thrown by function B

我正在 JavaScript 中进行尝试和捕捉练习。

这是我的代码

function getTime1() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(11111);
    }, 1000);
  });
}

function getTime2() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(22222);
    }, 1000);
  });
}

async function funB() {
  // try {
  let b = await getTime2();
  throw "B error";
  // } catch (e) {
  //   console.log("this" + e);
  // }
}

async function funA() {
  try {
    let a = await getTime1();
    funB();
  } catch (e) {
    console.log("that" + e);
  }
}
funA();

这是结果

Uncaught (in promise) B error

我想知道为什么funb和Funa中没有catch。谢谢

据我了解 try/catch 不适用于异步 :

"Because errorTest is async, it will always return a promise and will never begin execution exactly where you call it: it is asynchronous. errorTest returns, and you exit the try block, before a single line of code within errorTest is run. Therefore, your catch block will never fire, because nothing in errorTest would synchronously throw an exception."

来源:

因为异步将 return 一个 Promise,我相信你需要在 Promise 本身上使用 catch

funB().then((result) => {
    console.log(result);
}).catch((error) => {
    console.error(error);
});