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

时间:2019-03-04 11:46:42

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

我有一个arrow函数,它从api调用返回一些数据。我想将其包裹在一个尝试捕获块中,例如

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

3 个答案:

答案 0 :(得分:1)

将您的功能转换为 //below code works for me var httpProxy = require('http-proxy') var proxy = httpProxy.createProxy(); var options = { 'foo.com': 'http://foo.com:8001', 'bar.com': 'http://bar.com:8002' } require('http').createServer(function(req, res) { proxy.web(req, res, { target: options[req.headers.host] }); }).listen(80);

async

答案 1 :(得分:1)

您不能在获取时使用try catch,因为在try catch同步时fetch是异步的。因此,您的尝试捕获将始终通过。如果我们假设您收到响应,并且.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失败”

答案 2 :(得分:0)

尝试使用异步/等待

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