title: Angularjs promise inside a for loop
body: <p>I have the following code that loops through the list of reports, changes each one's name and does an updates. It works fine if there is only one report in the list, but if there are 2 reports, then only the 2nd one gets updated. </p>
  
  <p>When I looked at the network tab, I saw that for the 1st report, there was only a GET call, but for the 2nd report, there were both GET and PATCH calls.</p>
  
  <p>My suspicion is that in this async loop, the variable <code>thisReport</code> gets overwritten when the 2nd report's GET returns and then it goes on to update the 2nd report. The 1st report didn't get a chance to get updated.</p>
  
  <p>My question is how should I rewrite the code so all the reports in the list can get updated. Sorry about the newbie question. All advice are appreciated!</p>
  
  <pre><code>for (var i = 0; i &lt; $scope.listOfReports.length; i++) {
    var reportId = $scope.listOfReports[i].Id;
    if (reportId &gt; 0) {
      var thisReport = reportSvc.query({ key: reportId });
      thisReport.$promise.then(function (data) {
          thisReport.name = newValue;
          thisReport.$update({ key: reportId }).then(function () {
          });
      });
  }}
  </code></pre>