I'm trying to compare two approaches of using promises in angular after reading this article.
So I use this code to compare with/without using deferred. Note: the adress http://localhost:1337/error returns a response with an http 500 status and a message "error" as error data (it is the intended behavior).
.controller("HomeCtrl", function($q, $http) {
function doAsyncCallDeferred() {
var deferred = $q.defer();
$http.get("http://localhost:1337/error")
.catch(function(errorData) {
// error
deferred.reject(errorData.data);
});
return deferred.promise;
}
function doAsyncCall() {
return $http.get("http://localhost:1337/error")
.catch(function(errorData) {
// error
return errorData.data;
});
}
doAsyncCallDeferred()
.then(function (data) {
console.log("with deferred success");
console.log(data);
})
.catch(function(errorData) {
// data should be "error"
console.log("with deferred error");
console.log(errorData);
});
doAsyncCall()
.then(function (data) {
console.log("without deferred success");
console.log(data);
})
.catch(function(errorData) {
// data should be "error"
console.log("without deferred error");
console.log(errorData);
});
})
But I am confused by the result :
with deferred error
error
without deferred success
error
I was assuming that with both approaches, the catch callback would be executed, but it seems that it's not the case. Do anyone can explain this behavior please ?