catch 中的 return 语句后代码仍然执行吗?

iam*_*ynq 5 javascript node.js typescript

console.log('1');
await get()
    .then()
    .catch(() => {
        console.log('2');

        return;
    });
console.log('3');
Run Code Online (Sandbox Code Playgroud)

为什么控制台记录 1 2 3?我想在return语句之后,代码不会被执行?

Cer*_*nce 6

return只会终止当前函数。在这里,被 终止的函数return.catch回调。

由于.catch返回已解决的 Promise,因此awaited Promise 链将在解析时解析catch

如果您想在运行时停止外部catch函数,请catch返回您在外部检查的内容,例如:

(async() => {
  console.log('1');
  const result = await Promise.reject()
    .catch(() => {
      console.log('2');

      return 2;
    });
  if (result === 2) {
    return;
  }
  console.log('3');
})();
Run Code Online (Sandbox Code Playgroud)

或者抛出.catch一个错误,以便外部 Promise 链拒绝。由于正在await编辑,整个外部 Promise 将被拒绝:

const fn = async () => {
  console.log('1');
  const result = await Promise.reject()
    .catch(() => {
      console.log('2');
      throw new Error();
    });
  console.log('3');
};

fn()
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'))
Run Code Online (Sandbox Code Playgroud)

如果您.catch没有做任何实质性的事情,但您想要这种行为,那么完全忽略它通常是一个好主意。这样,当出现错误时,awaited Promise 将拒绝,函数将终止,并且错误可以由适当的使用者捕获。

const fn = async () => {
  console.log('1');
  const result = await Promise.reject();
  console.log('3');
};

fn()
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'))
Run Code Online (Sandbox Code Playgroud)