I wrote these tests to help me to understand how the HttpPromise object returned by the $http service works and how to utilize $q.
You will need to have nodejs installed and the karma command line executable installed with npm globally
- ensure node installed and available in your path.
- cd into the folder containing the package.json file
- npm install
To run the tests:
npm test
- defer() creates a new promise;
- For functions that already return a promise, such as $http, defer() is not necessary.
- Whether using defer() or not, the then method is still present.
- It is not necessary to use $q.resolve() if one is catching failures with $q.reject()
- not http errors though
- A .catch() can be used in lieu of the second parameter of the then() method.
- Data returned with $q.resolve() will be applied the input of the next success function within the next then() in the chain
- Data returned with a $q.reject() will be applied to the input of the next failure function within the next then() or optionally catch() in the chain.
The HttpPromise object's then() takes two parameters as shown below. Returning data from #1 is applied to the next then's #1. Returning data from #2 is applied to the next then's #2 (optionally one may omit #2 to ignore failures or to utilize a catch method instead).
- a function to handle success
- a function to handle failure
One often reads that this is an anti-pattern because the defer() is creating a new promise which is not necessary.
var p = $q.defer()
$http.get('someUrl')
.then(
function(response){
if(response.data === 'xyz') {
p.resolve(response.data);
} else {
p.reject('not xyz!')
}
},
function(err){
if(err.status !== 500){
p.resolve('123')
} else {
p.reject(err.status);
}
}
)
return p.promise;
Resolves are an input into the next then's success function. Rejects are an input into the next then's failure function (or catch)
With $q, one can reject or resolve in both the success and error portions.
return $http.get('someUrl')
.then(
function(response){
if(response.data === 'xyz') {
return response.data; // will be an input into the _success_ function of the next _then_
} else {
$q.reject('not xyz!')
}
},
function(err){
if(err.status !== 500){
$q.resolve('123')
} else {
return err.status; // will be an input into the _failure_ function of the next _then_
}
}
);
Resolves are an input into the next then's success function. Rejects are an input into the next then's failure function (or catch)
If one doesn't need to worry about rejecting within the success function or conversely resolving in the failure function of the then (or catch) method, $q is not needed.~~ Returning a value from either a then success
or then error
or catch
will always be an input into the next then's success function.
return $http.get('someUrl')
.then(
function(response){
return response.data // will be an input into the next _then's_ success function
},
function(err){
return err.status // will be an input into the next _then's_ success function
}
);