【问题标题】:How to wrap a try catch block inside an arrow function to call an api?如何将 try catch 块包装在箭头函数中以调用 api?
【发布时间】:2019-07-25 17:28:18
【问题描述】:

我有一个箭头函数,它从 api 调用返回一些数据。我想把它包在一个 try catch 块中,比如

const fetchEmployees = () => (
   try{
       fetch('http://localhost:6873/api/values', {
          method: 'GET',
          headers: {
            'content-type': 'application/json'
          }
       })
         .then(response => response.json())
         .then(names => { return names })
       } catch (error) {
           return error;
       }
  )

我怎么能这样做?我拥有的完美工作箭头功能是

const fetchEmployees = () => (
fetch('http://localhost:6873/api/values', {
    method: 'GET',
    headers: {
        'content-type': 'application/json'
    }
})
    .then(response => response.json())
    .then(names => names )
)

【问题讨论】:

  • 为什么不简单地在fetch 上使用catch
  • 你想捕捉什么错误。 .json() 失败?
  • 实际问题是您使用括号 () 而不是大括号 {} 作为箭头函数的主体 - 它仅适用于第二种情况,因为body 是一个单一的表达式。但你也应该 .catch 拒绝承诺。
  • 你真的想return error 来自catch 块吗?这不是一个好主意,你应该处理那里的错误而不是卖掉它。

标签: javascript function ecmascript-6 promise arrow-functions


【解决方案1】:

您不能在 fetch 上使用 try catch,因为 fetch 是异步的,而 try catch 是同步的。因此,您的 try catch 将始终通过。如果我们假设您收到响应,并且 .json() 失败,那么第二个参数是成功函数,第二个参数是失败函数,当 .json() 失败时执行

const fetchEmployees = () => (
  fetch('http://localhost:6873/api/values', {
      method: 'GET',
      headers: {
          'content-type': 'application/json'
      }
  })
      .then(response => response.json())
      .then(names => names, error => "json failed" )
)

fetchEmployees().then(success => {}, error => {})

这样,当你在第一个函数中调用 fetchEmployees 时,如果一切成功,就会执行,否则第二个函数会执行错误响应,在这种情况下是硬编码字符串“json failed”

【讨论】:

    【解决方案2】:

    把你的函数变成async一个:

    const fetchEmployees = async () => {
      try {
        const response = await fetch("http://localhost:6873/api/values", {
          method: "GET",
          headers: {
            "content-type": "application/json"
          }
        });
    
        const names = await response.json();
    
        return names;
      } catch (error) {
        return error;
      }
    };
    

    【讨论】:

      【解决方案3】:

      尝试使用异步/等待

      const fetchEmployees = async () => {
         try {
             let response = await fetch('http://localhost:6873/api/values', {
                method: 'GET',
                headers: {
                  'content-type': 'application/json'
                }
             });
             let json = await response.json();   
             return json;    
         } catch (error) {
           return error
         }
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-15
        • 1970-01-01
        • 1970-01-01
        • 2018-08-23
        • 2015-08-26
        • 2010-09-26
        • 2022-12-13
        • 1970-01-01
        相关资源
        最近更新 更多