Why $ .when (). Pipe (). Then () works, but not $ .when (). Then (). Then ()?

I'm still trying to wrap my head using jQuery Deferred objects and scratching my head on one specific issue. In the following code, I first tried linking deferred.then() , but it never worked. All three functions are performed immediately. Only after my employee pointed me to the pipe function did everything fall into place. The question is why pipe() works, 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 the code above: http://jsfiddle.net/eterpstra/yGu2d/

+7
source share
3 answers

This is how then() and pipe() work in your example:

then() returns the Deferred and calling then() in that one Deferred, you simply add a second callback to it, which will be called at the same time as the first

pipe() instead returns a new promise, allowing you to build a chain and why you get consecutive calls in this case


Take a look at the following resources for more information on pipe / then:

When should I use jQuery deferred "then" and when should I use the "pipe" method?

Promise Pipelines in JavaScript

+5
source

Since jQuery 1.8 then () returns a new Promise (same as pipe ()) instead of the same deferred as when () returns.

Change the jQuery version to 1.8.3 or higher in your example at:

http://jsfiddle.net/eterpstra/yGu2d

and

$.when(testDefer("Hi")).then(there).then(guy);

will work.

+6
source

You use .then in such a way that it is not used - you say that it is deferred when all that .then expects is a simple function to be added as a callback .

The .then method returns the original Deferred that has already been resolved. When Deferred resolves, all callbacks added using .then are executed immediately.

On the other hand, the .pipe function accepts either a set of functions or a promise (this is what you send it to), and decides based on the status of the original Deferred. The .pipe functionality is actually what you are looking for!

+2
source

All Articles