gpt4 book ai didi

angularjs - Angular $http promise 总是解决

转载 作者:可可西里 更新时间:2023-11-01 17:06:29 26 4
gpt4 key购买 nike

在每个使用 .then(successFunc).catch(errFunc) 的 $http 调用中(或者 then(successFunc, errFunc) then/success 总是被调用(promise 被成功解析)。

例子

$http.get('/some/resource') 
// /some/resource --> HTTP 400
.then(function(response)
{
console.log('success');
})
.catch(function(reason)
{
console.log('error');
})

// Console:
// - success

这是预期的行为还是导致这种行为的原因?

最佳答案

不,这不是预期的行为。通常它应该在 HTTP 2xx 上调用 .then() 和在 HTTP 4xx 上调用 .catch()HTTP 5xx(不确定其他)。

所描述的行为可能是由另一个 .catch() 返回已解决的 promise 引起的。

在一个稍微改变的例子中:

//In some Service:
function getResources()
{
$http.get('/some/resource')
// /some/resource --> HTTP 400
.then(function(response)
{
console.log('service success');
return response;
})
.catch(function(reason)
{
console.log('service error');
// IMPORTANT: although this is returned
// in a .catch() it returns a resolved promise
return reason;
});
}

//In some Controller:
someService.getResources()
.then(function(response)
{
console.log('controller success');
})
.catch(function(reason)
{
console.log('controller error');
});


// Console:
// - service error
// - controller success

请注意,这也可能是由已注册的 http 拦截器 引起的:

$httpProvider.interceptors.push(function($q)
{
return {
'response': function(response)
{
// do something
return response;
},
'responseError': function(rejection)
{
// do something
return rejection; // <-- this causes the problem
// instead do
return $q.reject(rejection);
}
}
}

关于angularjs - Angular $http promise 总是解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39468612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com