how to make a function wait for a asynchronous call to be completed?

Problem

I have an angularjs service to get my json data.

// Controller.js file
$scope.data=Events.query();

$scope.getEventtypes = function(){
angular.forEach($scope.data,function(value, key){
var arr = [];
if(key==$scope.month+$scope.year) {
for(var i=0; i<key.length; i++) {
arr.push(value[i].type);
$scope.eventtypes=arr.unique();
}
}
});
};

while trying to access the value[i].type it throws an error cannot read property type of undefined. I know it is because of the asynchronous call.

//i want to add success function like this
$http.get('').success(function(data) {
....
});

can anyone help me?? it will be better if u suggest to do something more efficient than this. Thank you

Problem courtesy of: Prashanth Suriyanarayanan

Solution

While @Mahbub suggestion is in the right direction (promises make it easier to coordinate asynchronous functions) it is not the only technique. Good, old callbacks will work as well. While promises are arguably more elegant API the bitter truth it that promises API is not supported as part of the $resource in he current version of AngularJS.

Theory aside, in your particular case you could simply use a callback and be done with it:

$scope.data=Events.query(function(data){

angular.forEach(data,function(value, key){
var arr = [];
if(key==$scope.month+$scope.year) {
for(var i=0; i<key.length; i++) {
arr.push(value[i].type);
$scope.eventtypes=arr.unique();
}
}
});
});

Solution courtesy of: pkozlowski.opensource

View additional discussion.