Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does $.when().pipe().then() work, but not $.when().then().then()?

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/

like image 224
eterps Avatar asked Sep 04 '12 22:09

eterps


People also ask

What is then () in JavaScript?

then() The then() method returns a Promise . It takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise .

What is deferred in JQuery?

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.

What is then in JQuery?

then() method in JQuery is used to add handlers which are to be called when the Deferred object is resolved, rejected, or in progress.

How do you use deferred?

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.


1 Answers

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.

like image 112
Alejandro Cobo Cobo Avatar answered Nov 04 '22 17:11

Alejandro Cobo Cobo