0

I have a code and i want to execute it in asynchronous manner, here is my code snippet

var arr = [1,2,7,4,5];
for(var i in arr)
{
var res = "";
var count =i;
$("#container").append("<div id='div_"+count+"'></div>");
$.get( qlink, function(retdata) {
res= retdata.value;
});
$("#div_"+count).html(res);  // Last line
}

Everything is executing fine But the problem here is in the "Last line" what is does is it takes the value of count as 5 for every iteration. Any suggestion? I want the execution to be parallel and parallely want the variable scope to be confined to that iteration only.

void
  • 36,090
  • 8
  • 62
  • 107
  • 3
    The real question is why you would do five ajax requests to the same URL and not just return all the content at once ? – adeneo Jul 01 '14 at 10:05
  • adeneo its not the actual code which i am running just a sample of the problem, its not the same url i am calling again and again its ofcourse different contained in another array. – void Jul 01 '14 at 10:11

3 Answers3

0
var arr = [1,2,7,4,5];
for(var i in arr)
{
 var res = "";
 var count =i;
 $("#container").append("<div id='div_"+count+"'></div>");
 $.ajax({
        url:"yoururl",
        sucess: function(result){
                 $("#div_"+count).html(result.value);
                }
       });
}
0

Move the last line into the handler function of "get" call:

var arr = [1,2,7,4,5];
for(var i in arr)
{
    var res = "";
    var count = i;
    $("#container").append("<div id='div_" + count + "'></div>");

    $.get( qlink, function(retdata) {
        res = retdata.value;
        $("#div_" + count).html(res);
    });
}
ovunccetin
  • 8,443
  • 5
  • 42
  • 53
0

The basic problem is is the wrong use of a closure variable and handling of the async value res

var arr = [1, 2, 7, 4, 5];
$.each(arr, function (i, val) {
    var $ct = $("<div id='div_" + val + "'></div>").appendTo("#container");
    $.get(qlink, function (retdata) {
        $ct.html(retdata.value);
    });
})
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531