Asynchrony inside a loop

I am using the jQuery API $.getJSON()to retrieve data from a given URL for a set of utilities. I would really like to find a way to reuse the code (everything is exactly the same) for each utility. Since the loop runs without respect for the ajax call, I could not find a way to save the loop value.

This description sucks, I know, so there is a piece of code here 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 a callback so that I can apply the correct syntax. Without this, all three loops run against the Water utility. I know why it does not work, I'm just wondering if there is a reasonable solution.

Thank.

+5
source share
3

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

, , - , , .

, ( ), , :

..., success: (function(type) {
    return function() {
        alert(type);
    }
}(type))

type . type , . alert, , , .. .

, , , ! , , .

+3

you can assign a "type" value to a member variable for each ajax request and test it with a keyword thisin the callback success function:

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];

  var jsonReq = $.getJSON( '/addresses/utilities/' + zip + '/' + type + '.json', null, function( data, status ) {
    alert( 'Processing ' + this.utilityType );
  });
  jsonReq.utilityType = type;
}
0
source

All Articles