jQuery的推迟不会调用,以便决心/ DONE回调 [英] jQuery Deferred not calling the resolve/done callbacks in order

查看:156
本文介绍了jQuery的推迟不会调用,以便决心/ DONE回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于jQuery的推迟不会调用,以便决心/ DONE回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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