The .success
and .error
methods ignore return values.
Consequently they are not suitable for chaining.
var httpPromise = $http
.get(/* some params */)
.success(function onSuccess(data, status, headers, config) {
var modifiedData = doModify(data);
//return value ignored
return modifiedData;
})
.error(function onError(data, status, headers, config) {
// error cases here
});
httpPromise.then(function onFullfilled(response) {
//chained data lost
//instead there is a response object
console.log(response.data); //original data
console.log(response.status); //original status
});
On the otherhand, the .then
and .catch
methods return a derived promise suitable for chaining from returned (or throw) values or from a new promise.
var derivedPromise = $http
.get(/* some params */)
.then(function onFulfilled(response) {
console.log(response.data); //original data
console.log(response.status); //original status
var modifiedData = doModify(response.data);
//return a value for chaining
return modifiedData;
})
.catch(function onRejected(response) {
// error cases here
});
derivedPromise.then(function onFullfilled(modifiedData) {
//data from chaining
console.log(modifiedData);
});
Response Object vs Four Arguments
Also notice that the $http
service provides four arguments (data, status, headers, config)
when it invokes the function provided to the .success
and .error
methods.
The $q
service only provides one argument (response) to the functions provided to the .then
or .catch
methods. In the case of promises created by the $http
service the response object has these properties:1
- data – {string|Object} – The response body transformed with the transform functions.
- status – {number} – HTTP status code of the response.
- headers – {function([headerName])} – Header getter function.
- config – {Object} – The configuration object that was used to generate the request.
- statusText – {string} – HTTP status text of the response.
Chaining promises
Because calling the then
method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs.2
Update
The .success
and .error
methods have been deprecated and removed from AngularJS V1.6.
For more information, see