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/
then() The then() method returns a Promise . It takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise .
Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.
then() method in JQuery is used to add handlers which are to be called when the Deferred object is resolved, rejected, or in progress.
Deferred method can be passed an optional function, which is called just before the method returns and is passed the new deferred object as both the this object and as the first argument to the function. The called function can attach callbacks using deferred. then() , for example.
Since jQuery 1.8 then() returns a new Promise (the same as pipe()) instead of the same Deferred that when() returns.
Change the jQuery version to 1.8.3 or above in your example at:
http://jsfiddle.net/eterpstra/yGu2d
and
$.when(testDefer("Hi")).then(there).then(guy);
will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With