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?
You aren’t passing the right thing to
setTimeout(). This won’t work because you are callingdfd.resolve()immediately and passing that result tosetTimeout()in this line:Instead, you need something like this:
which will not call the resolve until the timeout fires.