Reputation: 1081
I have a function that that returns a promise of an $http GET (the promise success/error is handled by the invoker). What I need is, given certain conditions and even though the $http is successful, to return an error (the invoker would catch this condition as a rejected promise).
In this plunk, I tried to return $q.reject() but this doesn't work.
http://plnkr.co/edit/iC3Wb1PBUFrXgPbTJyU0?p=preview
This is the 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();
});
Any ideas?
Upvotes: 5
Views: 6609
Reputation: 8725
$http.success()
and error()
are convenience shortcuts that are not 100% compliant with promises. Use vanilla promise then
instead:
$http(config).then(function(response){return $q.reject}, function onError(reason){})
Upvotes: 7
Reputation: 17385
Try this: http://plnkr.co/edit/hTNFjXXDfqQ7e7jvNMtg?p=preview
You return a deferred promise of your own and resolve/reject is on will
var defer = $q.defer();
$http(config)
.success(function (response, status, headers, config) {
console.log(response);
if (x == 1)
defer.reject('error');
else
defer.resolve(response);
})
.error(function (data, status, headers, config) {
});
return defer.promise;
Upvotes: 5