0

I have some code in angularJS like this:

$scope.myArray= [{name:"thomas", parentId: 1}, {name:"john", parentId: 2}]
for(var i = 0; i< $scope.myArray.length, i++){
    // I wish this code run as blocking code
    $http.get('getParentById'+$scope.myArray[i].parentId).then(function(result){
        if(result){
            $scope.myArray[i].parentName = result.data;
        }
    });
}

My intention very clearly, assigns parentName for each object get by Http request. But the problem is asynchronous in angularJs. I have tried many ways but it can not be fixed. Does anyone have a solution for this?

EDIT: I got an answer in the comment below. The solution is using angular.foreach()

NAM
  • 107
  • 3
  • 10
  • Start by using a block-scope iterator `i` rather than function scope, or even better, use the Array class method `forEach`. – tehhowch Nov 26 '19 at 12:09
  • Can you explain more clearly? What is using a block-scope iterator i? – NAM Nov 26 '19 at 12:14
  • If you are not familiar with block scope, you need to learn that yourself - there are a great number of webpages about it. Here it means that each loop had its own copy of `i` instead of sharing one. – tehhowch Nov 26 '19 at 12:23
  • I have used array foreach as you mentioned and it worked very well. Thank you very much – NAM Nov 26 '19 at 13:18
  • Feel free to post your solution as an answer and then accept it after the waiting period – tehhowch Nov 26 '19 at 13:46
  • Does this answer your question? [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Heretic Monkey Nov 26 '19 at 14:06
  • @tehhowch There are many duplicates of this question. You have the rep, please vote to close as such. – Heretic Monkey Nov 26 '19 at 14:06

0 Answers0