本文介绍了在 Promise 中,使用 catch 和 then 的第二个参数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这两种说法到底有什么区别?
What exactly is the difference between these two statements?
funcThatReturnsAPromise()
.then(() => { /* success */ })
.catch(() => { /* fail */ });
funcThatReturnsAPromise()
.then(() => { /* success */ }, () => { /* fail */ });
推荐答案
除了 .catch(fn)
作为 .then(null, fn)
的快捷方式之外,你的例子的不同之处在于
Besides .catch(fn)
being a shortcut for .then(null, fn)
, the difference in your examples is that
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)
*/ }
);
这篇关于在 Promise 中,使用 catch 和 then 的第二个参数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!