0

I have list of ids [1,2,3,4], I need to make update with this ids and with the answer from my update I need to make UI update to displayed list. I must update each row in my list async, once one id update finished I will make UI update for this row

my approach is to make for loop and to make $http request for each id

for(var i = 0 ; i < ids.length; i++){
     $http.get("api/update?Id=" + ids[i]).then(function (result) {
                            $scope.nodeUpdate = result;
    });
}

   $scope.$watch('nodeUpdate', function() {
      //update node result, the result will have node id+new data
   });

What do you think? This should work fine? Is there a better way to do it?

Thanks,

5
  • Why would you use a watch? Just call the function which "update node result" from the http callback function. Commented Oct 23, 2015 at 11:21
  • You are right, I can do it that way. Do you think this way I won't miss any result. What if 2 results are back at the same time? Commented Oct 23, 2015 at 19:21
  • JavaScript is single-threaded. There is no way for two things to happen at the same time. Commented Oct 23, 2015 at 20:06
  • OK...so each promise that will back gets it's "own" update function? Commented Oct 24, 2015 at 11:09
  • 1
    When a promise is resolved, the callbacks passed to then() is called. So yes, the function(result) passed to then() will be called 4 times: once for each id. Commented Oct 24, 2015 at 11:21

1 Answer 1

1

Better way to prevent code by creating anononyms function call stack.

for(var i = 0 ; i < ids.length; i++){
     (function()
       {
       $http.get("api/update?Id=" + id).then(function (result) {
            $scope.nodeUpdate = result;   
        });
      )(ids[i]);
}
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.