这是使用body.json()并获取状态代码的唯一方法吗?
let status;
return fetch(url)
.then((response => {
status = response.status;
return response.json()
})
.then(response => {
return {
response: response,
status: status
}
});这不起作用,因为它返回响应字段中的承诺:
.then((response)=> {return {response: response.json(), status: response.status}})发布于 2017-11-13 15:01:11
您的状态在第二个then中不可见。您可以在单个then中获得这两个属性。
json()向您返回一个新的承诺,因此您需要在该函数的结果的then中创建对象。如果你从一个函数中返回一个承诺,它将被实现,并将返回实现的结果--在我们的例子中是对象。
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(r => r.json().then(data => ({status: r.status, body: data})))
.then(obj => console.log(obj));
发布于 2017-11-13 15:16:04
上周我也遇到了同样的问题。.json方法向解析的JSON返回一个承诺,而不是解析的JSON本身。如果希望同时访问响应和解析的JSON,则需要使用以下嵌套闭包:
fetch(url)
.then(response => {
response.json().then(parsedJson => {
// code that can access both here
})
});或者,您可以使用async/await语法:
async function fetchTheThing() {
const response = await fetch(url);
const parsedJson = await response.json();
// code that can access both here
}当然,您需要检查错误,无论是使用.catch(...)调用还是使用带有async函数的try...catch块。您可以创建一个处理JSON和错误案例的函数,然后将其用于所有获取。例如,如下所示:
function fetchHandler(response) {
if (response.ok) {
return response.json().then(json => {
// the status was ok and there is a json body
return Promise.resolve({json: json, response: response});
}).catch(err => {
// the status was ok but there is no json body
return Promise.resolve({response: response});
});
} else {
return response.json().catch(err => {
// the status was not ok and there is no json body
throw new Error(response.statusText);
}).then(json => {
// the status was not ok but there is a json body
throw new Error(json.error.message); // example error message returned by a REST API
});
}
}我不认为这是最好的设计模式,但希望这澄清了fetch是如何工作的。
发布于 2020-09-19 17:57:45
对我来说,使用两种方法似乎是不必要的。
异步/等待可以很容易地完成任务。
fetch('http://test.com/getData')
.then( async (response) => {
// get json response here
let data = await response.json();
if(data.status === 200){
// Process data here
}else{
// Rest of status codes (400,500,303), can be handled here appropriately
}
})
.catch((err) => {
console.log(err);
})https://stackoverflow.com/questions/47267221
复制相似问题