0

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 () {
        });
    });
}}
2
  • 1
    Probably because by the time the first query is resolved, 'thisReport' is already referencing a new 'thisReport'. The same goes for the reportId. I think you've got some scoping issues going on either way. Commented Jul 20, 2016 at 21:38
  • yes @matmo that's what I thought too...any idea how to rewrite it to avoid scope issues? Commented Jul 21, 2016 at 14:25

1 Answer 1

1

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 () { });
     });
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.