这两个陈述之间究竟有什么区别?
funcThatReturnsAPromise()
.then(() => { /* success */ })
.catch(() => { /* fail */ });
funcThatReturnsAPromise()
.then(() => { /* success */ }, () => { /* fail */ });
答案 0 :(得分:8)
除了.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)
*/ }
);
答案 1 :(得分:5)
.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 */ });
答案 2 :(得分:3)
然后(..)取一个或两个参数,第一个用于实现 回调,第二个用于拒绝回调。如果是的话 省略或以其他方式作为非函数值传递,默认值 回调分别被替换。默认的履行回调 简单地传递消息,同时默认拒绝回调 简单地重新抛出(传播)它收到的错误原因。抓住(..) 仅将拒绝回调作为参数,并自动进行 如上所述,替换默认的履行回调。换句话说,它等于then(null,..):
p . then ( fulfilled );
p . then ( fulfilled , rejected );
p . catch ( rejected ); // or `p.then( null, rejected )`
然后(..)和catch(..)也创建并返回一个新的promise,它可以 用于表达Promise链流量控制。如果履行或 拒绝回调抛出异常,返回的承诺是 被拒绝。如果任何一个回调返回一个立即的非承诺, 非值的值,该值被设置为的履行 回报了承诺。如果履行处理程序专门返回一个 承诺或价值,该价值被解开并成为 决定退回的承诺。
-from"你不了解JS,Kyle Simpson