没有ajax调用可以使用jQuery的.when吗? [英] Is it possible to use jQuery's .when without an ajax call?

查看:84
本文介绍了没有ajax调用可以使用jQuery的.when吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://jsfiddle.net/f4hmL/235/

function showData() {
    alert("boop!");
}

function method1() {
    var dfd = $.Deferred();
    setTimeout(dfd.resolve(), 10000);
    return dfd.promise();
}

function method2() {
    var dfd = $.Deferred();
    setTimeout(dfd.resolve(), 6000);
    return dfd.promise();
}

$.when(method1(), method2()).then(showData);​

我希望只有当两个延迟对象都解决后才能看到boop,但我立即看到它。是否有可能实现这一目标? jQuery的when方法是正确使用的函数吗?

I was hoping to only see "boop" displayed when both deferred objects resolved, but I see it immediately. Is it possible to achieve this? Is jQuery's "when" method the right function to be using?

推荐答案

你没有把正确的东西传递给的setTimeout()。这不起作用,因为您立即调用 dfd.resolve()并将该结果传递给 setTimeout() in这一行:

You aren't passing the right thing to setTimeout(). This won't work because you are calling dfd.resolve() immediately and passing that result to setTimeout() in this line:

setTimeout(dfd.resolve(), 10000);

相反,你需要这样的东西:

Instead, you need something like this:

setTimeout(function() {dfd.resolve()}, 10000);

在超时发生之前不会调用解析。

which will not call the resolve until the timeout fires.

这篇关于没有ajax调用可以使用jQuery的.when吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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