一个循环内异步性

2023-09-10 17:24:22 作者:酒入りチョコ(洒心巧克力)

我使用jQuery的 $。的getJSON() API来获取给定的URL数据为一组实用工具。我真的想找到一种方法来重用code(这一切都完全一样),每个工具。由于循环执行,而不对于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.

这说明很烂,我知道,所以here'a一个code段定义它好一点:

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

我需要找到一种方法,将类型值传递给回调函数,所以我可以应用正确的语法。如果没有,在所有3个回路正在执行打击水工具。我知道为什么它的没有的工作,我只是想知道是否有一个合理的解决办法。

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.

感谢。

推荐答案

创建一个封闭

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));
}
相关推荐