title: jquery deferred in for loop
body: <p>So I have been working on jquery deferred but am having trouble when retrieving data in a loop. The deferred portion seems to only process the data from the final iteration. If there is only one item in the array, it fails as well, so I am not sure what is going on. </p>
  
  <p>I have various city names, and I am trying to get central coordinates for each city from the google maps reverse geocoded</p>
  
  <p>Here is my function that gets the central coordinates:</p>
  
  <pre><code>function getGroupLatLng(groupname){
      var deferred = new $.Deferred();
  
       geocoder.geocode( { 'address': groupname}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
                deferred.resolve(results);
  
            alert(results[0].geometry.location.lat());
        } else {
  
        }
  
      });
      return deferred.promise();
  }
  </code></pre>
  
  <p>This is where the function is called, and a div is appended once the result is returned:</p>
  
  <pre><code>var newGroupsLength = newGroups.length;
  
  for (i = 0; i &lt; newGroupsLength; i++) {
  
      newGroups[i]['counter']=counter;
      var locationName = newGroups[i]['name'];
      counter++;
      alert(locationName);
      $.when(getGroupLatLng(locationName)).then(function(results){
          alert("lat = "+results[0].geometry.location.lat());
          var lat=results[0].geometry.location.lat();
          var lng=results[0].geometry.location.lng();
          console.log(newGroups[i]); //this is running the proper number of times, but it logs the results from the final looped item, 'n' number of times. 
  
          newGroups[i]['lat']=lat;
          newGroups[i]['lng']=lng;
  
          var jsonArray=[];
          jsonArray = newGroups[i];
          var template = $('#groupsTemplate').html();
          var html = Mustache.to_html(template, jsonArray);
          $('#groups-container').append(html);
      });
  }
  </code></pre>
  
  <p>The problem I am having is that the deferred loop seems to process the last item in the for loop 'n' number of times, with 'n' being the number of items in the newGroupsLength array. Of course it should process each item one time.  If the deferred action is removed, it all works fine.</p>
  
  <p>Sincere thanks for any help. It is greatly appreciated</p>