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.6k
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 {
    // ...
  }
}
推荐问题