$ .Deferred chain

I hope to understand why I have a different behavior when you try to chain a deferred object directly than I do when I try to chain, store the object in a variable and call one or more deferred methods for that variable.

When saving the object in a variable, the value assigned to each function is the same (in the case of a code fragment below, 5) - that is, the values ​​are not filtered in this case. When directly connecting values, the values ​​are filtered ... so I don’t understand how to get filtering when setting up Deferred.pipe() in several different statements. And by reading jquery docs , this should be possible:

A deferred object is chained, similar to how a jQuery object is chained, but has its own methods. After creating the Deferred object, you can use any of the following methods by chaining directly from creating the object or storing the object in a variable and calling one or more methods for this variable.

What am I doing wrong?

Here is my code:

 <script type="text/javascript"> $(document).ready(function () { // This works as expected - alert(20) var defer = new $.Deferred(); defer.pipe(myFunction).pipe(myFunction).pipe(myAlert); defer.resolve(5); // This does not work as expected - alert(5) var defer2 = new $.Deferred(); defer2.pipe(myFunction); defer2.pipe(myFunction); defer2.pipe(myAlert); defer2.resolve(5); }); var myFunction = function (value) { return value * 2; } var myAlert = function (value) { alert('The value is ' + value); } </script> 
+4
source share
2 answers

The $.Deferred really connected to the chain, but in the second scenario you are not hooking anything; you simply assign multiple pipe to the $.Deferred object, which should execute independently when $.Deferred either allowed or rejected. In other words, you are ignoring the returned Promise object that contains the filtered / modified value that will be passed to the next .pipe() in the chain.

From docs :

The deferred.pipe () method returns a new promise that filters . status and values ​​pending through the function.

To achieve what you want in your second example, pipe result of the Promise instead of the original $.Deferred object:

 var defer2 = new $.Deferred(); var promise = defer2.pipe(myFunction); promise = promise.pipe(myFunction); // pipe and update promise promise.pipe(myAlert); defer2.resolve(5); 

Demo .

+3
source

Joao, I had the same case - an unknown number of pipes to be called up. here's how to do it - Asynchronous loop in JavaScript

-1
source

Source: https://habr.com/ru/post/1434970/


All Articles