Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What $q.defer() really does?

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?

like image 728
user3115001 Avatar asked Mar 01 '14 22:03

user3115001


1 Answers

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.

defer.promise // we get access to result of the deferred task

.then( // .then() calls success or error callback
    function(param) {
        alert("i something promised " + param);
        return "something";
    }); // u can use 1 or more .then calls in row

 defer.resolve("call"); //returns promise

Here example: http://jsfiddle.net/nalyvajko/HB7LU/29048/

like image 159
Vasyl Gutnyk Avatar answered Oct 05 '22 04:10

Vasyl Gutnyk