title: AngularJS: Using $q to fire ajax calls synchronously
body: <p>Is it possible to use $q to fire ajax requests synchronously in AngularJS?</p>
  
  <p>I have a long list of <code>vehicles</code>, each <code>vehicle</code> has <code>events</code> associated with them and I need to retrieve the <code>eventdetails</code> of each <code>event</code> when the user expands the listing.</p>
  
  <p>Right now, if the user expands the listing, I am firing up to 15 calls asynchronously and it seems to be causing issues with the API I'm consuming, so I'd like to see if performance is improved if I wait for each request finishes before firing the next.</p>
  
  <p>I'm attempting to implement <code>$q</code> to delay the next request until the previous is finished, however I can't seem to wrap my head around using the service, here is what I currently have:</p>
  
  <pre><code>// On click on the event detail expander
  $scope.grabEventDetails = function(dataReady, index) {
      if (dataReady == false) {
          retrieveEventDetails($scope.vehicles[index].events);
      }
  }
  
  var retrieveEventDetails = function(events) {
      // events is array
  
      var deferred = $q.defer();
      var promise = deferred.promise;
  
      var retrieveData = function(data) {
          return $http({
              url: '/api/eventdetails',
              method: 'POST',
              data: {
                  event_number: data.number
              },
              isArray: true
          });
      }
  
      _.each(events, function(single_event) {
          promise.then(retrieveData(single_event).success(function(data) {
              console.log(data);
          }));
      });
  }
  </code></pre>
  
  <p>This is still firing asynchronously, Where am I going wrong with this?</p>
  
  <p>I understand firing the requests synchronously isn't the best idea, at the moment I just want to see if performance is improved with the API at all.</p>