问题描述
我在react-native中使用fetch进行API调用.
I use fetch in react-native to make API calls.
我需要获取状态码(200,401,404)和响应数据.
I need to get status code (200 , 401, 404 ) and the response data.
这项工作是为了获取响应数据:
This work to get the response data :
return fetch(url)
.then(response => {
return response.json();
})
.then(res => {
console.log("reponse :", res); // <-------- res is ok with data
}) .catch(error => {
console.error(error);
return { name: "network error", description: "" };
});
现在我先进行调整,然后再获取状态代码,但数据不是我所需要的
Now i tweak the first then to get the status code but data is not what i except
return fetch(url)
.then(response => {
const statusCode = response.status;
const data = response.json();
return { statusCode, data };
})
.then(res => {
console.log("reponse :", res); // <-------- i get a "promise"
}).catch(error => {
console.error(error);
return { name: "network error", description: "" };
});
控制台日志:
{statusCode: 200, data: Promise}
推荐答案
response.json()
返回一个Promise,您应该等待直到它实现为止.为此,您可以将Promise.all
与两个元素组成的数组一起使用:statusCode
和response.json()
调用:
response.json()
returns a promise, you should wait until it will be fulfilled. To do that you can use Promise.all
with array of two elements: statusCode
and response.json()
call:
return fetch(url)
.then(response => {
const statusCode = response.status;
const data = response.json();
return Promise.all([statusCode, data]);
})
.then([res, data] => {
console.log(res, data);
})
.catch(error => {
console.error(error);
return { name: "network error", description: "" };
});
//编辑您可以创建一个处理响应的函数
//EDITyou can create a function who process the response
function processResponse(response) {
const statusCode = response.status;
const data = response.json();
return Promise.all([statusCode, data]).then(res => ({
statusCode: res[0],
data: res[1]
}));
}
并使用then()
return fetch(url)
.then(processResponse)
.then(res => {
const { statusCode, data } = res;
console.log("statusCode",statusCode);
console.log("data",data);
}) .catch(error => {
console.error(error);
return { name: "network error", description: "" };
});
这篇关于react-native取回状态代码+ json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!