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.
Asked
Active
Viewed 3,469 times
5
-
4This has been asked *a lot* on Stack Overflow; please read through the multitude of questions we have on the subject, and after that; please write up a question that doesn't duplicate the other questions on this subject; or edit this question to explain how it's not a duplicate. – George Stocker Jul 27 '15 at 18:59
-
1@f1best: see for example [Immediately return a resolved promise](http://stackoverflow.com/q/24794434/1048572) or [can't simply use ES6 promise to update data in ng-repeat?](http://stackoverflow.com/q/30835399/1048572) – Bergi Jul 27 '15 at 20:02
-
Related: [How does Angular $q.when work?](https://stackoverflow.com/questions/16770821/how-does-angular-q-when-work) – ggorlen May 21 '23 at 03:09
1 Answers
16
$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
}

Benjamin Gruenbaum
- 270,886
- 87
- 504
- 504

Tyler
- 11,272
- 9
- 65
- 105