Laguna
Laguna

Reputation: 3866

Angularjs promise inside a for loop

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.

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.

My suspicion is that in this async loop, the variable thisReport 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.

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!

for (var i = 0; i < $scope.listOfReports.length; i++) {
  var reportId = $scope.listOfReports[i].Id;
  if (reportId > 0) {
    var thisReport = reportSvc.query({ key: reportId });
    thisReport.$promise.then(function (data) {
        thisReport.name = newValue;
        thisReport.$update({ key: reportId }).then(function () {
        });
    });
}}

Upvotes: 0

Views: 1503

Answers (1)

Laguna
Laguna

Reputation: 3866

After more research, I got to know that this is a closure inside loop pattern, and I fixed this by creating a function for the logic that was originally inside the loop. new code below

for (var i = 0; i < $scope.listOfReports.length; i++) {
 var reportId = $scope.listOfReports[i].Id;
 UpdateValue(reportId, ANewName);    
}

function UpdateValue(reportId, newName)
{
   if (reportId > 0) {
     var thisReport = reportSvc.query({ key: reportId });
     thisReport.$promise.then(function (data) {
        thisReport.name = newName;
        thisReport.$update({ key: reportId }).then(function () { });
     });
   }
}

Upvotes: 1

Related Questions