Q: How to handle asynchronous calls inside looping? I know this question is already answered in someway, but am unable to get my stuff working.
  YammerFunctionality.getMessagesInThread(msg.id,$scope.older_ID).then(function(response){
            var obj=response.data.messages;
            var messages=[];
            var reverseMessage=obj.reverse();
            var promises=[];
            for(var i=0;i<reverseMessage.length;i++){
                 var deferred = $q.defer();
                 promises.push(deferred.promise);
                if(reverseMessage[i].replied_to_id) {
                    YammerFunctionality.getUserInfo(reverseMessage[i].sender_id).then(function(response){
                        reverseMessage[i].sender_name=response.data.full_name;
                        messages.push(reverseMessage[i]);
                        deferred.resolve();
                    },function(error){
                        deferred.reject(error);
                    });
                }
            }
            $q.all(promises).then(function () {
                 console.info('All resolved');
                 $state.go('yammermessage',{messages:messages});
            },function(){
                showAlert("Thread error");
            });

    },function(error){
        showAlert("Yammer Error while opening Thread.");
    });

I am trying to get all messages from particular thread and once found I am trying to get user details of same.
Problem is in for loop where I get the thread and call user service , by the time user service is executed index moves till last count and hence my code gets broken.
reverseMessage[i].sender_name
says " reverseMessage[i]" is undefined since i has moved to last position in array. [If length 20, then i=20 and no data available]
Help is appreciated !

A: You cannot use the variable i inside your promise. you need to create a closure function and pass the variable to that function. Try the below code.
 for(var i=0;i<reverseMessage.length;i++){
             var deferred = $q.defer();
             promises.push(deferred.promise);
         function closure(i){    
            if(reverseMessage[i].replied_to_id) {
                YammerFunctionality.getUserInfo(reverseMessage[i].sender_id).then(function(response){
                   reverseMessage[i].sender_name=response.data.full_name;
                    messages.push(reverseMessage[i]);
                    deferred.resolve();
                },function(error){
                    deferred.reject(error);
                    });
                }
            }
 closure(i);
        }

