What $q.defer() really does?

2019-03-29 18:15发布

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?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-29 18:45

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/

查看更多
放我归山
3楼-- · 2019-03-29 19:06

Angular's $q service is based on the Javascript library Q. 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:

If a function cannot return a value or throw an exception without blocking, it can return a promise instead. A promise is an object that represents the return value or the thrown exception that the function may eventually provide. A promise can also be used as a proxy for a remote object to overcome latency.

查看更多
登录 后发表回答