简体   繁体   中英

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 !

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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM