参考答案

Promise 的 then 方法和 catch 方法都是用于处理 Promise 的 rejected 状态的情况。它们的区别在于:

  1. then 方法的第二个参数

如果 Promise 的状态变为 rejected,then 方法的第二个参数会被调用。该参数是一个函数,可以接收一个参数,即 Promise 返回的错误信息。

例如:

function asyncFunction() { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('Something went wrong')); }, 1000); }); } asyncFunction() .then( result => console.log(result), error => console.error(error) );

在上述代码中,当 Promise 被 reject 时,then 方法的第二个参数会被调用,并打印出错误信息。

  1. catch 方法

catch 方法相当于 then 方法的第二个参数,也是用于处理 Promise 的 rejected 状态的情况。不同之处在于,catch 方法可以链式调用,而不需要在每次调用 then 方法时都传递第二个参数。

例如:

function asyncFunction() { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('Something went wrong')); }, 1000); }); } asyncFunction() .then(result => console.log(result)) .catch(error => console.error(error));

在上述代码中,当 Promise 被 reject 时,catch 方法会被调用,并打印出错误信息。

因此,then 方法的第二个参数和 catch 方法都是用于处理 Promise 的 rejected 状态的情况,但前者需要在每次调用 then 方法时都传递第二个参数,而后者则可以链式调用。