The .success and .error methods ignore return values .
Therefore, they are not suitable for the chain .
var httpPromise = $http .get() .success(function onSuccess(data, status, headers, config) { var modifiedData = doModify(data);
On the other hand, the .then and .catch return a derived promise that is suitable for a chain of returned (or discarding) 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 Against Four Arguments
Also note that the $http service provides four arguments (data, status, headers, config) when calling the function provided by the .success and .error methods.
The $q service provides one argument (response) to the functions provided by the .then or .catch . In the case of promises created by the $http service, the response object has the following properties: 1
- data - {string | Object} is the response body transformed using the conversion functions.
- status - {number} - The HTTP status code for the response.
- headers - {function ([headerName])} - the function of the header receiver.
- config - {Object} - the configuration object that was used to generate the request.
- statusText - {string} - response text of the HTTP response.
Chain promises
Since calling the then method of the promise returns a new derived promise, it's easy to chain from promises. You can create chains of any length, and since a promise can be resolved using another promise (which will delay its further resolution), you can pause / delay the resolution of promises at any point in the chain. This allows you to implement powerful APIs. 2
source share