I'm learning about Angular JS and on the moment I'm trying to understand about promises and async programming and I have this doubt about $q.defer()
. My point is the following: usually when people work with promises they do something like that, considering that $q is already available
function someAsyncFunction() {
var deferred = $q.defer();
/* Do things and if everything goes fine return deferred.resolve(result)
otherwise returns deferred.reject()
*/
return deferred.promise;
}
What is this really doing? When we do var deferred = $q.defer()
it imediately switches all the execution of that function to another thread and return the promise being a reference to the results of this operation that is still performing there?
Is this the way we should think about when creating async methods?
With $q u run functions asynchronously. Deferred objects signals that something, some task is done.
var defer = $q.defer();
// we create deferred object, which will finish later.
Here example: http://jsfiddle.net/nalyvajko/HB7LU/29048/
Angular's
$q
service is based on the Javascript libraryQ
. You can read more about it in the Q documentation, or read the code in the github repo. I think this part snipped from the introduction to the documentation explains it best: