react-native fetch返回状态码json
发布时间:2020-12-15 09:32:47 所属栏目:百科 来源:网络整理
导读:我在react-native中使用fetch来进行API调用. 我需要获取状态代码(200,401,404)和响应数据. 这项工作来获取响应数据: return fetch(url).then(response = { return response.json();}).then(res = { console.log("reponse :",res); // -------- res is ok wi
我在react-native中使用fetch来进行API调用.
我需要获取状态代码(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: "" }; }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |