前端面试题 - 54. Promise then 第二个参数和catch的区别是什么?

613 阅读1分钟
  1. Promise 内部报错,reject 抛出错误后,由于就近原则,then 的第二个参数会先捕获到异常,catch 则无法获取异常。
  2. 但如果是 then 的第一个参数抛出错误,then 的第二个参数会捕获不到,只有 catch 能捕获。

解释下1.的原因,据MDN知: calling obj.catch(onRejected) 内部 calls obj.then(undefined, onRejected)).

示例

先模拟一个Promise

function fetchUser(userId: number): Promise<any> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const users = [
        { id: 1, name: 'Alice' },
        { id: 2, name: 'Bob' },
        { id: 3, name: 'Charlie' }
      ];
      const user = users.find(u => u.id === userId);
      if(user) {
        resolve(user);
      } else {
        reject(new Error(`reject错误,${userId}未找到`));
      }
    }, 1000);
  });
}
  • then抛出错误,catch捕获
fetchUser(1)
  .then(
    (user) => {
      console.log(user.name);
      throw new Error('测试then中抛出错误')
    },
    (error) => {
      console.error("then第二个参数捕获:", error.message);
    }
  ).catch(error => {
    console.error("catch捕获:" + error.message);
  });

image.png

  • promise错误(reject),就近捕获(这里有第二个参数,所以第二个参数捕获)
fetchUser(4)
  .then(
    (user) => {
      console.log(user.name);
      throw new Error('测试then中抛出错误')
    },
    (error) => {
      console.error("then第二个参数捕获:", error.message);
    }
  ).catch(error => {
    console.error("catch捕获:" + error.message);
  });

image.png

  • promise错误(reject),就近捕获(这里没有第二个参数,所以catch捕获)
fetchUser(4)
.then(
  (user) => {
    console.log(user.name);
    throw new Error('测试then中抛出错误')
  }
).catch(error => {
  console.error("catch捕获:" + error.message);
});

image.png