$.when()
requires arguments that are a deferred or promise. It will then resolve itself when all those promises passed as arguments are resolved. When you pass it something that is not a promise, $.when()
really has no idea when it's done so can't do it's job.
If you really want to use setTimeout()
with the promises API, then you probably want to wrap it so that it returns a promise that is resolved after the timer fires. Then, you can use it just like the $.ajax()
calls.
Here's a promise wrapper for setTimeout()
. It returns a promise that is resolved after the timer has fired and the callback has been called and the value it is resolved with is the return value from the callback:
function promiseSetTimeout(fn, t) {
var d = $.Deferred();
setTimeout(function() {
d.resolve(fn());
}, t);
return d.promise();
}
Then, you could use promiseSetTimeout()
with $.when()
:
function fnOne() {
return promiseSetTimeout(function(){ return "one"; }, 1000);
}
function fnTwo() {
return promiseSetTimeout(function(){ return "one"; }, 1000);
}
$.when( fnOne(), fnTwo() ).then(function( a1, a2 ) {
console.log(a1, a2);
});
Working demo: http://jsfiddle.net/jfriend00/HskLh/