title: How to loop through Ajax Requests inside a JQuery When - Then statment?
body: <p>I am trying to load a bunch of data from an API Async and when all the data is loaded I want to trigger an event that all the data is loaded. The problem I am having is that the API I am using limits the number of response objects to five. And I would potentially need to retrieve 30-40 response objects. </p>
  
  <p>So what I want to do is create a when - then statement that loops trough the data items and makes request for every five items then when all the items are loaded I want to fire a loaded event. The issue I am having is that the when-then statement is completing before the success of the ajax request.</p>
  
  <p>onto the code I have tried. </p>
  
  <pre><code> function loadsLotsOfStats(stats, dataType, eventName, dataName, callback) {
       var groupedStats = [];
       while (stats.length &gt; 0) {
           groupedStats.push(stats.splice(0, 5).join('/'));
       }
      j$.when(
          groupedStats.forEach(function (d) {
              loadJSONToData(model.apiUrl.replace("{IDS}", d), "json", "", dataName, function (d) { /*console.log(d);*/ }, true)
          })
      ).then(function () {
          j$(eventSource).trigger('dataLoaded', eventName);
      });
  </code></pre>
  
  <p>The loadJSONToData function is basically just a wrapper function for an Async $.ajax.</p>
  
  <p>so yeah the event is getting triggered before the data is actually loaded. Also for some reason if I try to put for loop right in the when( statement it through a syntax error? </p>
  
  <p>Does anyone have any advice on how I could make a bunch of Ajax requests and wait until they all are compeleted before triggering an event? Or a away to fix what I currently have? </p>
  
  <p>Thanks in advance for the help. </p>