title: How to work with loop of promises in jquery?
body: <p>I am working on an application where I need to compile a table of weather data which has the weather information for the same day for the last 10 years. I am using Forecast.io which provides an easy API to query old weather data:</p>
  
  <pre><code>https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE,TIMESTAMP
  </code></pre>
  
  <p>So basically I have to pass my key, lat, long and timestamp for which I need the data for.</p>
  
  <p>My code look like:</p>
  
  <pre><code>function bindweatherHistoryTable(){
          console.log(historyData);
          var weatherHistoryTable = rivets.bind($('#weatherHistoryTable'), {data: historyData});
      }
  
      var historyData = {};
      for(i = 1; i &lt;= 10; i++){
          fetchHistoryUrl = '//api.forecast.io/forecast/' + forecastToken + '/' + farmLat + ',' + farmLng + ',' + (moment().subtract(i, 'years').valueOf() / 1000).toFixed(0);
  
          var promise = $.ajax({
              method: 'GET',
              dataType: 'JSONP',
              url: fetchHistoryUrl,
              success: function(response){
                  var data = {
                      temperature: response.currently.temperature,
                      dewPoint: response.currently.dewPoint,
                      humidity: response.currently.humidity,
                      windSpeed: response.currently.windSpeed,
                      windBearing: response.currently.windBearing,
                      pressure: response.currently.pressure
                  };
  
                  historyData[moment().year() - i] = data
  
                  console.log(data);
              }
          });
  
          promise.done(function(){ console.log('hello') });
  
          if(i == 10){
              console.log(i);
              promise.done(bindweatherHistoryTable());
          }
      }
  }
  </code></pre>
  
  <p>So basically I am using a for loop to query last 10 years and then compile the data into a single object and finally bind the object to the view using Rivets.</p>
  
  <p>The object is being compiled because I am logging every ajax call object that is formed. I am also using the <code>promise.done()</code> method to log <code>'hello'</code> after every ajax call was a success.</p>
  
  <p>I am also specifying that if it is the last iteration, the promise should log the final history object and bind it to the history table.</p>
  
  <p>Every call is success. I can see the output object for every call in the console. I can also see the 'hello' in the log after every promise is resolved.</p>
  
  <p>But the final object which should be logged after everything is logged in the very beginning before any of the ajax calls are made. I am new to promises and I don't understand why. I just want to take the final object and use it in my view by binding it to my table. What am I doing wrong and what can I do to fix it?</p>