Javascript 在承诺中,什么';使用catch和then的第二个参数有什么区别?

Javascript 在承诺中,什么';使用catch和then的第二个参数有什么区别?,javascript,promise,Javascript,Promise,这两种说法到底有什么区别 funcThatReturnsAPromise() .then(() => { /* success */ }) .catch(() => { /* fail */ }); funcThatReturnsAPromise() .then(() => { /* success */ }, () => { /* fail */ }); 然后(..)接受一个或两个参数,第一个用于实现 回调,第二个用于拒绝回调。如果其中一个是 省略或以

这两种说法到底有什么区别

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


funcThatReturnsAPromise()
  .then(() => { /* success */ }, () => { /* fail */ });
然后(..)接受一个或两个参数,第一个用于实现 回调,第二个用于拒绝回调。如果其中一个是 省略或以其他方式作为非函数值传递,默认值 回调分别被替换。默认实现回调 只需传递消息,而默认的拒绝回调 简单地重新引用(传播)它接收到的错误原因。捕获(…) 仅将拒绝回调作为参数,并自动 如前所述,替换默认的实现回调。换句话说,它等价于then(null,…):

然后(…)和catch(…)也创建并返回一个新的承诺,它可以 用于表示承诺链流量控制。如果满足或 拒绝回调抛出异常,返回的承诺为 拒绝。如果其中一个回调返回立即的非承诺, 非thenable值,该值设置为 回报承诺。如果履行处理程序专门返回 承诺或可实现的价值,该价值被展开并成为 退回承诺的决议

-从“你不知道JS,Kyle Simpson

除了
.catch(fn)
的快捷方式,然后(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)
等于
。然后(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 */ });

有更好的细节和答案,但我很感谢这一点,因为它完全符合我将如何表述这个问题:)谢谢你解释,我只是想找到一些文档,说明如果我传入错误函数,它是如何有益的。然后()第二个参数
。catch(fn)
等于
。然后(未定义,fn)
不是
。然后(null,fn)
。我检查了这个实现,它是null,不管规范说它可能不是的functionsecond参数。然后在时也会触发。然后的第一个参数抛出一个errorNo,@koo。它不是。请检查jsbin:
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 */ });