Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronicity within a loop

Tags:

jquery

ajax

I'm using jQuery's $.getJSON() API to retrieve data from a given URL for a set of utilities. I'd really like to find a way to reuse the code (it's all exactly the same) for each utility. Since the loop is executing without respect to the ajax call, I haven't been able to find a way to retain the looping value.

That description sucks, I know, so here'a a code snippet that defines it a little better:

var utility_types = [ 'Electricity', 'Gas', 'Water' ];

/** Retrieve known utility providers for the given zip code */
for( var i = 0; i < utility_types.length; i++ ) {
  var type = utility_types[i];

  $.getJSON( '/addresses/utilities/' + zip + '/' + type + '.json', null, function( data, status ) {
    alert( 'Processing ' + type );
  });
}

I need to find a way to pass the type value into the callback so I can apply the correct syntax. Without that, all 3 loops are executing against the "Water" utility. I know why it's not working, I'm just wondering whether there's a reasonable workaround.

Thanks.

like image 932
Rob Wilkerson Avatar asked Mar 19 '11 16:03

Rob Wilkerson


1 Answers

Create a closure

var utility_types = [ 'Electricity', 'Gas', 'Water' ];

function getCallBack(type){
   return function(data,status){
     alert( 'Processing ' + type );
   }
}

/** Retrieve known utility providers for the given zip code */

for( var i = 0; i < utility_types.length; i++ ) {
  var type = utility_types[i];

  $.getJSON( '/addresses/utilities/' + zip + '/' + type + '.json', null, getCallBack(type));
}
like image 133
Zimbabao Avatar answered Sep 28 '22 06:09

Zimbabao