Reputation: 6291
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
Upvotes: 0
Views: 208
Reputation: 123739
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...
Upvotes: 1