如何在箭头函数中包装 try catch 块来调用 api?

Rai*_*doy 5 javascript function promise ecmascript-6 arrow-functions

我有一个箭头函数,它从 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;
       }
  )
Run Code Online (Sandbox Code Playgroud)

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

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

小智 3

您不能在 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 => {})
Run Code Online (Sandbox Code Playgroud)

像这样,当您在第一个函数中调用 fetchEmployees 时,如果一切成功,则将执行第二个函数,否则第二个函数将执行并显示错误响应,在本例中为硬编码字符串“json failed”