【问题标题】:In a Promise, what's the difference between using catch and the 2nd argument of then? [duplicate]在 Promise 中,使用 catch 和 then 的第二个参数有什么区别? [复制]
【发布时间】:2017-02-25 08:14:13
【问题描述】:

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

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


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

【问题讨论】:

标签: javascript promise


【解决方案1】:

then(..) 接受一个或两个参数,第一个用于实现 回调,第二个用于拒绝回调。如果是 省略或以其他方式作为非函数值传递,默认值 分别替换回调。默认的履行回调 简单地传递消息,而默认的拒绝回调 简单地重新抛出(传播)它收到的错误原因。抓住(..) 仅将拒绝回调作为参数,并自动 如刚才讨论的那样,替换默认的履行回调。换句话说,它等价于 then(null,..) :

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

then(..) 和 catch(..) 也创建并返回一个新的 Promise,它可以 用于表示 Promise 链流控制。如果履行或 拒绝回调有一个异常抛出,返回的承诺是 被拒绝。如果任一回调返回一个立即的、非 Promise, non-thenable 值,该值被设置为 回报的承诺。如果履行处理程序专门返回一个 promise 或 thenable 值,该值被解包并成为 返回的承诺的解决方案。

——来自“你不知道 JS,凯尔·辛普森”

【讨论】:

    【解决方案2】:

    除了.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)
      */ }
    );
    

    【讨论】:

    【解决方案3】:

    .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 */ });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2013-11-09
    • 2014-07-19
    • 2018-05-14
    • 2019-09-04
    相关资源
    最近更新 更多