我在react-native中使用fetch来进行API调用. 我需要获取状态代码(200,401,404)和响应数据. 这项工作来获取响应数据: return fetch(url).then(response = { return response.json();}).then(res = { console.log("repons
我需要获取状态代码(200,401,404)和响应数据.
这项工作来获取响应数据:
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: "" }; });
现在我调整第一个然后获取状态代码但数据不是我除了
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()调用:
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: "" }; });
//编辑
您可以创建一个处理响应的函数
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: "" }; });