Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of $q.when in angularjs?

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.

like image 631
fablexis Avatar asked Dec 08 '22 02:12

fablexis


1 Answers

$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
}
like image 124
Tyler Avatar answered Dec 11 '22 08:12

Tyler