我如何获取Profise对象中从Fetch Api返回的错误值? [英] How can i get errors value inside Promise object which return from Fetch Api?
本文介绍了我如何获取Profise对象中从Fetch Api返回的错误值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的提取请求.
fetch(deafaultUrl + '/v1/users/',
{
headers: {
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(userInfoParams)
})
.then(function(response) {
console.log(response);
console.log(response.json());
// not working never go into this function
response.json().then(function(value) {
console.log('access promise');
console.log(value); // "Success"
});
if (response.status !== 200 && response.status !== 201) {
throw new Error("Bad response from server");
}
})
.then(function(json){
console.log("succeed json re");
console.log(json);
dispatch(update_user(json));
})
所以当我控制台这个console.log(response.json());
我明白了
但是Promise功能似乎无法锻炼.
But it seems like Promise function doesnot workout.
那么我该如何在[[PromiseValue]]内部获取错误对象?
So how can i get errors Object inside [[PromiseValue]]?
谢谢!
推荐答案
要从诺言中获取错误,您可以这样做:
To get the error from the promise, you can do it like this:
promise.then(function(data) {
}, function(error) {...}
OR
要获得承诺错误,您还可以使用.catch()块
To got promise error you can also use .catch() block
.then(){...}
.catch(){..}
永远不要去这部分,因为服务器已经发送了响应
Never going to this part because server already sent the response
.then(function(response) {
console.log(response);
console.log(response.json());
// not working never go into this function
response.json().then(function(value) {
console.log('access promise');
console.log(value); // "Success"
});
您可以通过以下方式编写代码:
You can write your code in this way:
fetch(deafaultUrl + '/v1/users/', {
headers: {
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(userInfoParams)
})
.then(function(response) {
// if request is successful
}
.catch(err){
// if got error
}
});
这篇关于我如何获取Profise对象中从Fetch Api返回的错误值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文