运行 catch 块中的异步回调是反模式吗?

Is it anti-pattern to run asynchronous callbacks in catch blocks?

像这样捕获错误是运行异步回调的反模式吗?

await something()
   .catch(async (err) => {
      console.error(err);
      await otherStuff();
   });

你这样做的方式是。在承诺中,您应该 return 承诺而不是使回调异步并等待它。

我认为不是,因为您可以在 catch 后面调用 .then。有时 throw 只是进入不同的操作分支,但最后它的偏好。

await something()
   .catch((err) => {
      console.error(err);
      return otherStuff();
   }).then(res => {
  // work with data
});

如果你的意图是让整个表达都永远不会拒绝——也就是说,避免需要

try {
  await something()
   .catch(async (err) => {
      // ...
} catch(e) {
  // handle
}

那么如果 otherStuff 呼叫有可能被拒绝,那么您现在正在做的事情就不安全了。如果 otherStuff 可能会拒绝,那么您应该确保捕获 抛出的可能错误,例如

await something()
   .catch(async (err) => {
      console.error(err);
      await otherStuff();
   })
   .catch(handleOtherStuffErrors)

虽然只有一个 await 的异步函数没有那么有用 - 考虑只返回 Promise:

await something()
   .catch((err) => {
      console.error(err);
      return otherStuff();
   })
   .catch(handleOtherStuffErrors)

像这样的链接捕获很奇怪,但这并不是不可能的,所以不要笼统地声明它是否天生就是坏的。