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?
A Promise executor should call only one resolve or one reject . Once one state is changed (pending => fulfilled or pending => rejected), that's all. Any further calls to resolve or reject will be ignored.
If the Promise rejects, the second function in your first . then() will get called with the rejected value, and whatever value it returns will become a new resolved Promise which passes into the first function of your second then. Catch is never called here either.
We must always add a catch() , otherwise promises will silently fail. In this case, if thePromise is rejected, the execution jumps directly to the catch() method. You can add the catch() method in the middle of two then() methods, but you will not be able to break the chain when something bad happens.
A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.
$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){})
updated plunker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With