关于javascript:在Promise中,使用catch和第二个参数之间的区别是什么?

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

本问题已经有最佳答案,请猛点这里访问。

这两个陈述之间究竟有什么区别?

1
2
3
4
5
6
7
funcThatReturnsAPromise()
  .then(() => { /* success */ })
  .catch(() => { /* fail */ });


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


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

1
2
3
4
5
6
7
8
9
10
11
12
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
*/
})

而第二个是

1
2
3
4
5
6
7
8
9
10
11
12
13
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)

但是您的代码示例之间存在差异:

1
2
3
4
5
6
7
8
9
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(..) takes one or two parameters, the first for the fulfillment
callback, and the second for the rejection callback. If either is
omitted or is otherwise passed as a non-function value, a default
callback is substituted respectively. The default fulfillment callback
simply passes the message along, while the default rejection callback
simply rethrows (propagates) the error reason it receives. catch(..)
takes only the rejection callback as a parameter, and automatically
substitutes the default fulfillment callback, as just discussed. In other words, it’s equivalent to then(null,..) :

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

then(..) and catch(..) also create and return a new promise, which can
be used to express Promise chain flow control. If the fulfillment or
rejection callbacks have an exception thrown, the returned promise is
rejected. If either callback returns an immediate, non-Promise,
non-thenable value, that value is set as the fulfillment for the
returned promise. If the fulfillment handler specifically returns a
promise or thenable value, that value is unwrapped and becomes the
resolution of the returned promise.

- 来自"你不懂JS,凯尔辛普森