Deferred对象和它自己的promise对象之间有什么区别? [英] What's the difference between a Deferred object and its own promise object?

查看:223
本文介绍了Deferred对象和它自己的promise对象之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们创建一个简单的Deferred对象:

Let's create a simple Deferred object:

defer = $.Deferred( function ( defer ) {
    setTimeout( defer.resolve, 3000 );
});

上述Deferred对象将处于挂起状态3秒,然后切换到已解决状态(此时将调用绑定到它的所有回调)。

The above Deferred object will be in the "pending" state for 3 seconds, and then switch to the "resolved" state (at which point all the callbacks bound to it will be invoked).

让我们也检索该Deferred对象的承诺:

Let's also retrieve the promise of that Deferred object:

promise = defer.promise();

现在,要添加一个Deferred对象解析后将要调用的回调,我们可以使用 .done() .then()。但是,我们可以在Deferred对象本身或其自己的promise对象上调用此方法 both

Now, to add callbacks which are going to be invoked once the Deferred object is resolved, we can use .done() or .then(). However, we can invoke this method both on the Deferred object itself or its own promise object.

defer.then( handler );

promise.then( handler );

在这两种情况下,处理程序函数将被调用(在这种情况下3秒后)。

In both cases, the handler function will be invoked (after 3 seconds in this case).

如果我们在时使用 $。,我们可以再次传递Deferred对象本身或其promise对象:

If we use $.when, we can again pass the Deferred object itself or its promise object:

$.when( defer ).then( handler );

$.when( promise ).then( handler );

同样,上面两行代码没有区别。

Again, there is no difference between the above two lines of code.

现场演示: http://jsfiddle.net/G6Ad6/

所以,我的问题是因为我们可以调用 .then() .done( Deferred对象本身上的等等,因为我们可以将该Deferred对象传递到 $。when(),这是什么意思 .promise()并检索promise对象? promise对象的目的是什么?为什么功能上存在这种冗余?

So, my question is since we can invoke .then(), .done(), etc. on the Deferred object itself and since we can pass that Deferred object into $.when(), what's the point of .promise() and retrieving the promise object? What's the purpose of the promise object? Why is there this redundancy in functionality?

推荐答案

它创建了一个密封的延迟值副本,没有 .resolve() .reject()方法。从文档

It creates a "sealed" copy of the deferred value, without the .resolve() and .reject() methods. From the documentation:


deferred.promise()方法允许异步函数阻止其他代码干扰其内部请求的进度或状态。

The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.

当对要修改的值没有意义时使用它。例如,当jQuery发出AJAX请求时,它返回一个promise对象。在内部, .resolve()原始 Deferred 对象的sa值,用户使用promise来观察。

It's used when it doesn't make sense for the value to be modified. For example, when jQuery makes an AJAX request it returns a promise object. Internally it .resolve()s a value for the original Deferred object, which the user observes with the promise.

这篇关于Deferred对象和它自己的promise对象之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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