1

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?

FrakyDale
  • 647
  • 8
  • 22
  • exact duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Bergi Apr 26 '14 at 20:13
  • also have a look at [Why is using “for…in” with array iteration such a bad idea?](http://stackoverflow.com/q/500504/1048572) – Bergi Apr 26 '14 at 20:14
  • Thanks the first example clarified my problem! i think a comment can't be marked as correct right? – FrakyDale Apr 26 '14 at 20:45

2 Answers2

1

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.

MD. Sahib Bin Mahboob
  • 20,246
  • 2
  • 23
  • 45
  • Please use the code example that the OP has posted, not some artificial unrelated example. Also, it is good practise to make the closed-over variable the parameter of the IEFE. – Bergi Apr 26 '14 at 20:58
  • @Bergi thanks for the best practise observation. Updated code snippet – MD. Sahib Bin Mahboob Apr 27 '14 at 09:57
0

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);
        }
    });
  });
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Not like this, no. A context should be an object (even though primitive values do work in ES5). – Bergi Apr 26 '14 at 20:14
  • @Bergi, read the question once again. Now read the answer. And the documentation of the $.ajax function and the meaning of the `context` parameter. – Darin Dimitrov Apr 26 '14 at 20:15
  • What would I spot by reading it again? I know what the problem is (see the linked duplicate). The solution would be to create a closure. Using the context you can provide to `$.ajax` could work as well, but `this` values should be objects in general. – Bergi Apr 26 '14 at 20:17
  • @Bergi, you seem to have completely misunderstood my answer. You also seem to be missing some knowledge about the jQuery library, the `$.ajax` function and the meaning of the `context` parameter which would solve the OP's problem in this particular scenario. – Darin Dimitrov Apr 26 '14 at 20:17
  • I fear I have understood it (and I see that it's working), but I think passing primitive strings as the context is an antipattern. You might as well not pass a `context` property at all and just use `this.data.name` (the config object is the default context as far as I recall) – Bergi Apr 26 '14 at 20:19
  • 1
    @Bergi, do you understand the meaning of the `context` parameter? Do you understand what `this` is inside the `success` callback if you do not specify a `context` parameter? Judging from your comments apparently you don't. So I invite you to read the documentation and familiarize yourself a little better before commenting and downvoting answers so fast. – Darin Dimitrov Apr 26 '14 at 20:20
  • I've read both the docs and the code of `$.ajax`, and know very well how [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) works. To cite: "*`context`. Type: **PlainObject**. This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings (`$.ajaxSettings` merged with the **settings passed** to `$.ajax`)*" – Bergi Apr 26 '14 at 20:23