async的fn写throw会被promise.catch捕获到吗?

const fn = async function() {
  throw 1;
};

fn()
  .then(data => console.log('then: ' + data))
  .catch(data => console.log('catch: ' + data))
  .finally(data => console.log('finally'));

// catch: 1
// finally

请问这么写规范吗?

这样写catch确实可以捕获到,但是不知道这么写是不是规范的?

不用promise,想用async,同时想和promise一样,有 then catch finally 的处理

阅读 2.5k
2 个回答

async就是promise的语法糖,用then和awit其实是一样的,你也可以这样写

try {
    await fn()
} catch(e) {
    console.log(e);
} finally {
    console.log('finally');
}

async 里可以 try-catch 捕获错误。

async fn() {
  try {
    // ...
  } catch (e) {
    // ...
  } finally {
    // ...
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题