I'm still trying to wrap my head around using JQuery's Deferred objects, and am scratching my head at one particular problem. In the following code, I initially tried to chain deferred.then()
but it never worked. All three functions execute at once. Only after my co-worker pointed me to the pipe
function did things fall into place. Question is, why does pipe()
work, but not then()
?
var otherDefer = function(msg){return function(){return testDefer(msg)}};
var there = otherDefer("there,");
var guy = otherDefer("guy.");
function testDefer(msg) {
var deferred = $.Deferred();
pretendAjaxCall( function() {
$('<li>'+msg+'</li>').appendTo('#msgOut');
deferred.resolve();
});
return deferred.promise();
}
function pretendAjaxCall(callback) {
setTimeout(callback,1500);
}
$.when(testDefer("Hi")).pipe(there).then(guy);
I also tried return deferred
instead of return deferred.promise()
when using when().then().then()
.
jsFiddle for above code: http://jsfiddle.net/eterpstra/yGu2d/