自动错误传递给异步函数

Automatic error passing on async functions

我有一些 async 函数在等待一些可能会被拒绝的承诺,我想将所有错误传递给函数返回的承诺。 JS 会自动执行此操作吗?

例如:

async foo(){
  bar_result = await bar();
  baz_result = await baz();
  return 'ok';
}

foo()
  .then(console.log)
  .catch(console.error);

如果 bar()baz() 被拒绝,在上面的例子中会发生什么?直觉上,他们会在 .catch(console.error) 行被捕获...

我的替代想法是将函数的内容包围在 try 块中,然后 catch(err){ throw err; },但它看起来多余...

在一个 async 函数中,如果一个 Promise 被 awaited,并且 Promise 拒绝,该函数将立即终止,并且它返回的 Promise 将被拒绝(具有相同的值被拒绝的 awaited 承诺)。您的函数将按预期运行 - 如果 barbaz 拒绝,console.error 将导致记录拒绝(并且不会调用 console.log)。