JS Fetch:如何 return 响应正文或错误?
JS Fetch: How to return response with body or error?
我正在努力将此代码从 ajax 移至获取。我想调用 API 和
- 不return直到完成
- return状态为
的响应对象
- return 响应对象 json
- return 带有错误消息的响应对象(如果存在)
此代码在完成之前 returning 导致未捕获的错误,并强制浏览器重新绘制 (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')
它 returns 响应。
//
已编辑,添加状态
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;
}
我正在努力将此代码从 ajax 移至获取。我想调用 API 和
- 不return直到完成
- return状态为 的响应对象
- return 响应对象 json
- return 带有错误消息的响应对象(如果存在) 此代码在完成之前 returning 导致未捕获的错误,并强制浏览器重新绘制 (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')
它 returns 响应。
// 已编辑,添加状态
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;
}