Question

I have something like this:

for(k in array){
 var importantData = array[k];

  $.post('user/list',{name:importantData.username},function(data){
      console.log('UID of '+importantData.username+' is:'+data.id);
  });
}

The problem is with "importantData" var, when i use it inside post callback it is always the last value, so i get something like:

UID of michelle is 11

UID of michelle is 6

UID of michelle is 23

¿How can encapsulate that var to get the real data of each case?

Was it helpful?

Solution

You can create a scope for each iteration and deal with this problem. A simple example can be like this :

for (var i =0; i<10 ; i++){
    (function(j){             
         $.get('https://stackoverflow.com',function(){
           console.log("I am from callback with the value of j ",j);
         })

     })(i);
}

Updated the code sample with passing arguments to IIFE.

OTHER TIPS

Use the $.ajax method and set the context parameter:

for(k in array) {
    var username = array[k].username;
    $.ajax({
        url: 'user/list',
        type: 'POST',
        data: { name: username },
        context: username,
        success: function(result) {
            // Here "this" will be the value you passed as context
            console.log('UID of '+ this + ' is:' + result.id);
        }
    });
  });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top