Multiple ajax requests in sequence using a recursive function and executing a callback function after all requests have completed

I have a comma separated list of names. I want me to want to invoke a server request for all names in a sequence and store the result inside an array. I tried and it works when I have the number of names that are on the line.

See Here - It Works When I Know the Number of Names

Now I want this code to be shared. If I add one name to this line, it should process automatically without adding any code for the ajax request.

See Here - This is what I tried. It does not work as expected.

shoppingList = shoppingList.split(","); var result = []; function fetchData(shoppingItem) { var s1 = $.ajax('/items/'+shoppingItem); s1.then(function(res) { result.push(new Item(res.label,res.price)); console.log("works fine"); }); if(shoppingList.length == 0) { completeCallback(result); } else { fetchData(shoppingList.splice(0,1)[0]); } } fetchData(shoppingList.splice(0,1)[0]); 

Problem

I do not understand how to determine that all promise objects have been resolved so that I can call the callback function.

+1
javascript ajax recursion
source share
3 answers

To make ajax requests sequentially, you have to put the recursive call into the callback:

 function fetchList(shoppingList, completeCallback) { var result = []; function fetchData() { if (shoppingList.length == 0) { completeCallback(result); } else { $.ajax('/items/'+shoppingList.shift()).then(function(res) { result.push(new Item(res.label,res.price)); console.log("works fine"); fetchData(); // ^^^^^^^^^^^ }); } } fetchData(); } 

or do you really use promises and do

 function fetchList(shoppingList) { return shoppingList.reduce(function(resultPromise, shoppingItem) { return resultPromise.then(function(result) { return $.ajax('/items/'+shoppingItem).then(function(res) { result.push(new Item(res.label,res.price)); return result; }); }); }, $.when([])); } 

( updated jsfiddle )


Note that in the requirements of the task, there is no need to execute ajax requests. You can also let them work in parallel and wait until they all run out :

 function fetchList(shoppingList) { $.when.apply($, shoppingList.map(function(shoppingItem) { return $.ajax('/items/'+shoppingItem).then(function(res) { return new Item(res.label,res.price); }); })).then(function() { return Array.prototype.slice.call(arguments); }) } 

( updated jsfiddle )

+1
source share
 // global: var pendingRequests = 0; // after each ajax request: pendingRequests++; // inside the callback: if (--pendingRequest == 0) { // all requests have completed } 
0
source share

I changed your code to minimum so that it works - Click here .

Please note that your last statement will not be fulfilled, since the subject promise will not be resolved linearly. Thus, the sequence of elements will change.

0
source share

All Articles