首页 > 解决方案 > 使用 async/await 时如何在嵌套的 Promise 中捕获错误

问题描述

async function thisThrows() {
  return new Promise((resove, reject) => {
    throw new Error("Thrown from thisThrows()");
  });
}

async function thatThrows() {
  return new Promise(async(resolve, reject) => {
    try {
      await thisThrows();
    } catch (err) {
      throw err;
    }
    console.log('reached here');
    resolve(true);
  });
}

async function run() {
  try {
    await thatThrows();
  } catch (e) {
    console.error('catch error', e);
  } finally {
    console.log('We do cleanup here');
  }
}

run();

我的情况是我不想要语句console.log('reached here'); 解决(真);如果先前的语句抛出错误,则应执行。我尝试了几种组合,但没有运气。run 方法应该捕获错误。在我上面的代码中运行方法catch方法没有执行

标签: javascripttypescript

解决方案


推荐阅读