在Promise中,使用catch和它的第二个参数有什么区别?

In a Promise, what's the difference between using catch and the 2nd argument of then?

本文关键字:参数 第二个 什么 区别 Promise 使用 catch      更新时间:2023-09-26

这两个语句到底有什么区别?

funcThatReturnsAPromise()
  .then(() => { /* success */ })
  .catch(() => { /* fail */ });

funcThatReturnsAPromise()
  .then(() => { /* success */ }, () => { /* fail */ });

除了.catch(fn).then(null, fn)的快捷方式外,您的示例中的区别在于

funcThatReturnsAPromise()
  .then(() => { /* success */ })
  .catch(() => { /* fail */ });
// is equivalent to
const p1 = funcThatReturnsAPromise()
const p2 = p1.then(() => { /* success */ })
const p3 = p2.catch(() => { /* 
   executed if p1 is rejected
   executed if p2 is rejected 
*/ })

而第二个是

funcThatReturnsAPromise()
  .then(() => { /* success */ }, () => { /* fail */ });
// equivalent to
const p1 = funcThatReturnsAPromise()
const p2 = p1.then(
  () => { /* success */ },
  () => { /*
     executed if p1 is rejected
     (p2 will be actually resolved by the result of this function only when p1 is rejected)
  */ }
);

.catch(foo) = .then(undefined, foo)

但是你的代码样本之间有一个区别:

funcThatReturnsAPromise()
  .then(() => { /* success case of funcThatReturnsAPromise */ })
  .catch(() => { /* both fail case of funcThatReturnsAPromise 
                     and fail case of "then" function */ });

funcThatReturnsAPromise()
  .then(() => { /* success case of funcThatReturnsAPromise */ }, 
        () => { /* fail case of funcThatReturnsAPromise */ });

then(…)接受一个或两个参数,第一个参数用于实现回调,第二个是拒绝回调。如果有一个是省略或作为非函数值(默认值)传递Callback分别被替换。默认的执行回调简单地传递消息,而默认的拒绝回调只是重新抛出(传播)它接收到的错误原因。抓住(. .)只接受拒绝回调作为参数,并且自动替代默认的实现回调,正如刚才讨论的那样。换句话说,它相当于then(null,..):

p . then ( fulfilled );
p . then ( fulfilled , rejected );
p . catch ( rejected ); // or `p.then( null, rejected )`

then(..)和catch(..)也创建并返回一个新的promise,它可以表示承诺链的流量控制。如果履行或拒绝回调会抛出异常,返回的承诺是拒绝。如果任何一个回调返回一个即时的非承诺,non-then值,该值被设置为返回的承诺。如果执行处理程序特别返回Promise或then值,则该值被打开并成为返回的承诺的解析。

-选自《你不知道JS》,Kyle Simpson