-->

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

2019-07-20 01:54发布

问题:

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:

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.