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

How to wrap a try catch block inside an arrow function to call an api?

我有一个箭头函数,它 returns 来自 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 )
)

尝试使用async/await

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
   }
}

将您的函数变成 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;
  }
};

您不能在 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"