Chain callback using deferred and pipe

I am trying to associate a callback with pipes using deferred ones. Everything seems to be working fine, but in callback2 it returns me the data from callback1. This is what the code looks like:

var getCall1 = function() { return $.ajax(url, { type: "GET", data: { }, contentType: "application/json", dataType: "json" }); } var getCall2 = function () { return $.ajax(url, { type: "GET", data: {}, contentType: "application/json", dataType: "json" }); } var callback1 = function (data) { alert('call 1 completed'); }; var callback2 = function (data) { alert('call 2 completed'); }; $.when(getCall1()).done(callBack1).pipe(getCall2()).done(callBack2); 

What am I missing here?

- Edit -

If I break them down into two pending calls, it works, but then why use the chain and the handset?

 $.when(getCall1()).done(callBack1); $.when(getCall2()).done(callBack2); 

- The right way to do this is

 var getCall1 = function() { return $.ajax(url, { type: "GET", data: { }, contentType: "application/json", dataType: "json" }); }.pipe(function (d){return d}); var getCall2 = function () { return $.ajax(url, { type: "GET", data: {}, contentType: "application/json", dataType: "json" }); }.pipe(function (d){return d}); var callback1 = function (data) { alert('call 1 completed'); }; var callback2 = function (data) { alert('call 2 completed'); }; $.when(getCall1, getCall2).done(function(d1, d2){ callback1(d1); callback2(d2); }); 
+4
source share
2 answers

You should write pipe(getCall2) , not pipe(getCall2()) . deferred.pipe () expects the callback to return deferred rather than deferred. Which makes sense, since the point is in the request chain (i.e., only start the second ajax call after the first is completed), and you will only get a delay after you start the action.

0
source

What I understand in your code, you want to call getCall2 only if getCall1 successful.

So your code seems good. I tried this in jsFiddle (with a simpler example) and it works fine for me:

http://jsfiddle.net/PG3aN/

This may be a dumb question, but are you sure that getCall1 and getCall2 should not just return the same result from the server? This may explain why you get the same data in callbacks 1 and 2.

Another question, in your last code example you write

 var getCall1 = function() { return $.ajax(url, { type: "GET", data: { }, contentType: "application/json", dataType: "json" }); }.pipe(function (d){return d}); 

Does the last channel replace something with the behavior of your code?

And a final note about your last code example, the expected result does not match. In this code, you wrote that you call callback1 and callback2 only if both getCall1 and getCall2 succeed. This is not the same as your first code.

Edit : new jsFiddle with real asynchronous result

http://jsfiddle.net/PG3aN/1/

0
source

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


All Articles