0

I'm building a very basic app with AngularJS. One of the things I need to do is remove items from a list. In an attempt to do this, I've written the following code:

$scope.removeItem = function(item) {
  var toRemove = -1;
  angular.forEach($scope.items, function(_item, key) {
    if (item === _item) {
      toRemove = key;
      return false;
    }
  });       

  if (toRemove >= 0) {
    $scope.items.splice(i, 1);
    return true;
  }
  return false;
};

This seems to be working. However, my data set is relative small. The thing I can't figure out is the .forEach. Does that function operate asynchronously? In other words, could my code below the angular.forEach execute before the .forEach has completed? I keep hearing about asynchronous operations. However, I don't understand when that happens and when it doesn't.

Thank you

1 Answer 1

1

No, it is not asynchronous. angular.forEach does not run asynchronously. You code below the forEach cannot run before forEach is done. It is assured. One more thing is you dont have to do a return false in the forEach iteration function. It is of no use in your case, it will still run the entire loop even if your first item matches the condition.

i think you probably misunderstood forEach to be an asynchronous operation possibly because of the function you registered. It is just an iteration function that you can use to evaluate each iteration.

Example for asynchronous functions is $timeout (setTimeout), $interval (setInterval), promise callbacks, ajax call backs, animationFrames etc...

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.