$ q.defer()的作用是什么? [英] What $q.defer() really does?

查看:298
本文介绍了$ q.defer()的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Angular JS,此刻我正试图了解Promise和异步编程,并且我对$q.defer()存有疑问.我的意思是:通常,当人们与诺言一起工作时,考虑到$ q已经可用,他们会做类似的事情

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;
}

这到底在做什么?当我们执行var deferred = $q.defer()时,它会立即将该函数的所有执行切换到另一个线程,并返回对仍在此处执行的该操作的结果的引用的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?

推荐答案

使用$ q,您可以异步运行函数. 延迟的对象发出信号,表明已完成某些任务.

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

这里是例子: http://jsfiddle.net/nalyvajko/HB7LU/29048/

这篇关于$ q.defer()的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆