jQuery的推迟不会调用,以便决心/ DONE回调回调、决心、jQuery、DONE

2023-09-10 19:10:24 作者:叮当猫

code例如: http://jsfiddle.net/MhEPw/1/

我有两个jQuery的递延对象。

I have two jQuery Deferred objects.

我想有一个以上的异步的要求发生了 - 他们都跑我想要的回调(的.done函数)是为了运行后,他们在指定不幸的是,他们根本不是为了运行。

I want to have more than one 'async' request happening - and after they all run I want the callbacks (the .done functions) to be run in order they were specified in. Unfortunately they don't run in order.

也许我找的一些功能在这里,递延不提供?

Maybe I am looking for some functionality here that Deferred doesn't provide?

推荐答案

您需要做的是连接所有的请求,一个主延迟对象并在其承诺,所有注册的回调。主延迟对象需要听取各个请求,并解决相应。实现这一点的最简单的方法是定义所有前面的推迟的对象以避免鸡和蛋的问题:

What you need to do is link all of your request with one master deferred object and register all of your callbacks on its promise. The master deferred object would need to listen to the individual requests and resolve accordingly. The simplest way to achieve this would be to define all of the deferred objects up front to avoid the chicken and egg problem:

var d1 = $.Deferred();
var d2 = $.Deferred();
var def = $.when(d1, d2);

def.done(function() {
    alert(1);
});
setTimeout(function() {
    d1.resolve();
}, 3000);

def.done(function() {
    alert(2);
});
setTimeout(function() {
    d2.resolve();
}, 1000);

小提琴: http://jsfiddle.net/pVVad/

更改递延对象定义的顺序是可能的,但它将使这个例子要复杂得多。

Changing the order of deferred objects definitions is possible but it would make the example much more complicated.

 
精彩推荐
图片推荐