我有一个箭头函数,它从 api 调用返回一些数据。我想把它包装在一个 try catch block 中,比如
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 上使用 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”
关于javascript - 如何将 try catch block 包装在箭头函数中以调用 api?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54982606/