What is the purpose of $ q.when in angularjs?
1 answer
$q.when
takes a promise or simple value and converts it to a promise. If it's already a promise, it just returns it.
This is useful if you don't know if the object you are 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 this case, it would be useful to use $q.when
to handle the return so that you get a value from 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
}
+8
source to share