JQuery Deferred - getting the result of chained ajax calls

the next problem - I need to call the ajax function a number of times, and when all the functions are finished, get all the results in an array. I came up with this:

function doAjax(xx){ var xdata = {json: $.toJSON({name: xx}), delay: 1}; return $.ajax({ url:"/echo/json/", data:xdata, type:"POST" }); } var carr = [doAjax('a'),doAjax('b'),doAjax('c'),doAjax('d')] var result = []; $.when( carr ) .done(function(data){ console.log(data); $.each(data, function(ix,val){ console.log(val.name); }); }); 

Spell here: http://jsfiddle.net/Fkd9n/

Everything seems to be working fine, "console.log (data)" writes out objects with response text, but "console.log (val.name)" is always "undefined". So, how to combine all the results into one array after all the calls are completed?

Thanks!

+4
source share
2 answers

If you know how many Ajax-Calls you have, just use $ .when ()

 $.when(doAjax('a'),doAjax('b'),doAjax('c'),doAjax('d')) .then(function(result_a,result_b,result_c,result_d) { console.log("Result from query a: " + result_a); console.log("Result from query b: " + result_b); console.log("Result from query c: " + result_c); console.log("Result from query d: " + result_d); }); 

If you do not know how many ajax calls you will have, you can manage your pending objects yourself.

 // altered version of doAjax() function doAjax(number,dObject) { var xdata = {json: $.toJSON({name: number}), delay: 1}; $.ajax({ url:"/echo/json/", data:xdata, type:"POST", success: function(data) { results.push(data); dObject.resolve(); } }); } // array that will contain all deferred objects var deferreds = []; // array that will contain all results var results = []; // make the ajax calls for (var i = 0; i < someNumber; i++) { var dObject = new $.Deferred(); deferreds.push(dObject); doAjax(i,dObject); } // check if all ajax calls have finished $.when.apply($, deferreds).done(function() { console.log(results); }); 

The magic comes with the apply () function, which makes the array arguments to the function.

+7
source

You can use the pipe function to process the resulting data.

 $.when.apply($, carr).pipe(function(){ console.log(arguments); return $.map(arguments, function(item){return item[0]}); }) .done(function(data){ console.log(data); $.each(data, function(ix,val){ console.log(val.name); }); });​ 

http://jsfiddle.net/Fkd9n/6/

+4
source

All Articles