Is it possible to use jQuery's .when without a

2019-07-20 02:12发布

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);​

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?

1条回答
放荡不羁爱自由
2楼-- · 2019-07-20 02:49

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.

查看更多
登录 后发表回答