Orchestration of Nested AJAX Calls In Each Loop

http://stackoverflow.com/q/27144249/1144203

HTML

<script src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script>
<div id="test">

</div>

JavaScript

$(function(){
  // test data
  var data = {
    results: [
      {requesterId: 1, assigneeId: 1},
      {requesterId: 2, assigneeId: 2},
      {requesterId: 3, assigneeId: 3},
      {requesterId: 4, assigneeId: 4}]
  };
    
  var fakeRequesters = [
    {id : 1, name : 'John'},
    {id : 2, name : 'Mary'},
    {id : 3, name : 'Bob'},
    {id : 4, name : 'Tina'},
  ];
  
  var fakeAssignees = [
    {id : 1, name : 'Lina'},
    {id : 2, name : 'Betty'},
    {id : 3, name : 'Tom'},
    {id : 4, name : 'Kim'},
  ];
    
  // Pretend this function is calling http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests(" + data.RequesterId + ")/CreatedBy
  // It will return a requester's ID and name, given an index in the fakeRequesters array.
  function retrieveITRequestsCreatedBy(index){
    return $.ajax('/echo/json/', {
      type: 'post',
      contentType: 'application/json',
      data: {json: $.toJSON({requester: fakeRequesters[index]})}
    });
  }
    
    // Pretend this function is calling http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests(" + data.AssignedToId + ")/AssignedTo
  // It will return an assignee's ID and name, given an index in the fakeAssignees array.
  function retrieveITRequestsAssignedTo(index){     
    return $.ajax('/echo/json/', {
      type: 'post',
      contentType: 'application/json',
      data: {json: $.toJSON({assignee: fakeAssignees[index]})}
    });
  }
    
  // Add all the Deferrred objects to an array
  deferreds = []
  $.each(data.results, function(index){
    deferreds.push(retrieveITRequestsCreatedBy(index));
    deferreds.push(retrieveITRequestsAssignedTo(index));        
  });
        
  // Invoke all the Deferred objects.
  $.when.apply($, deferreds)
   .then(function(){ // this will get invoked after all asynchronous ajax calls are completed
      $.each(arguments, function(){
        jQuery("#test").append(this[0]);
      });
   })
});