我有一个返回 $http GET promise 的函数( promise 成功/错误由调用者处理)。我需要的是,给定某些条件,即使 $http 成功,也返回错误(调用者会将此条件捕获为被拒绝的 promise )。
在这个 plunk 中,我试图返回 $q.reject() 但这不起作用。
http://plnkr.co/edit/iC3Wb1PBUFrXgPbTJyU0?p=preview
这是 JavaScript:
app.controller("ctrl", function($scope, $http) {
var getUrl = function() {
var config = {
method: 'GET',
url: 'some.txt'
};
var x = 1; // if x == 1 the http should fail
return $http(config).success(function(response, status, headers, config) {
console.log(response);
if (x == 1) return $q.reject('error');
}).error(function(data, status, headers, config) {});
};
var init = function() {
var promise = getUrl();
promise.then(function() {
alert('OK');
}, function() {
alert('error');
});
};
init();
});
有什么想法吗?
最佳答案
$http.success()
和 error()
是并非 100% 符合 promise 的便捷快捷方式。使用 vanilla promise then
代替:
$http(config).then(function(response){return $q.reject}, function onError(reason){})
关于javascript - 成功时拒绝 $http promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28076258/