JS Fetch:如何返回响应与正文或错误?



我正在努力从ajax获取这段代码。我想调用一个API和

  • 不返回,直到完成
  • 返回状态为的响应对象
  • 用json返回响应对象
  • 返回响应对象,如果存在则返回错误消息此代码在完成之前返回,导致未捕获的错误,并强制浏览器重新绘制(Chrome)。我不知道为什么。如果我缓慢地逐步执行代码,它总是完成的。
function getAPI(url, requestOptions) {
return fetch(url, requestOptions).then((response) => {
return response.json().then(json => {
response.json = json;
console.log(response);
return response;
})
.catch(error => {
console.error('Error:', error);
response.error = error;
return response;
});
}).catch(error => {
console.error('Error:', error);         
response.error = error;
return response;
});
}

我想你想要得到这个结果

async function getAPI(url, requestOptions) {
let result;
await fetch(url, requestOptions)
.then(response => response.json())
.then(response => result = response)
.catch(error => console.error('Error:', error))
return result;
}

使用:

await getAPI('https://jsonplaceholder.typicode.com/todos/1')

返回响应

//编辑,添加状态

async function getAPI(url, requestOptions) {
let result;
await fetch(url, requestOptions)
.then(response => response.json())
.then(response => result = { status: 'success', response })
.catch(error => result = { status: 'error', error })
return result;
}

相关内容

最新更新