【问题标题】:Difference between the two scenarios mentioned below? [duplicate]下面提到的两种情况之间的区别? [复制]
【发布时间】:2021-01-17 23:39:27
【问题描述】:

案例 1:

fetch('/foo')
   .then((res) => console.log(res), err => console.log(err))

案例 2:

fetch('/foo')
   .then(res => console.log(res))
   .catch(err => console.log(err))

这两种情况有什么区别?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    第一个没有链接,第二个没有链接

    fetch('/foo')
           .then(res => console.log(res))
          .catch(err => console.log(err))
    

    正在使用承诺链,.catch 真正的意思是.then(null, handler)

    检查this MDN page(在chaining部分下)

    ...
    then 的参数是可选的,catch(failureCallback)then(null, failureCallback) 的缩写。您可能会看到这用箭头函数表示:

    换句话说,第二个只是简写:

    fetch('/foo')
           .then(res => console.log(res))
           .then(null, err => console.log(err))
    

    所以区别只是使用了链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      相关资源
      最近更新 更多