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/
This is how
then()andpipe()work in your sample:then()returns Deferred and by callingthen()on this same Deferred you simply add a second callback to it which will be called simultaneously with the first onepipe(), instead, returns new Promise allowing you to build a chain and that’s why you get sequential calls in this caseTake a look at the following resources for more info about pipe/then:
When should I use jQuery deferred's "then" method and when should I use the "pipe" method?
Promise Pipelines in JavaScript