I have read the documentation of $q.when in the angularjs official docs, but I don´t understand yet what is the purpose of $q.when and its way to manage a response.
$q.when
takes a promise or a plain value and converts it to a promise. If it already was a promise it simply returns it.
It is useful if you don't know whether the object you're dealing with is a promise or not. For example, you might have an if/else statement where one path returns a promise but another path returns a value directly. In that case, it would be good to use $q.when
to handle the return such that you get a value out of it whether it's a promise or not.
For example:
function getData(){
if(cachedData) return $q.when(cachedData); // converts to promise
else return $http.get("/dataUrl"); // make HTTP request, returns promise
}
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