使用jQuery循环数据时调用异步函数

时间:2012-06-15 10:58:50

标签: jquery loops asynchronous

Stack上有很多这个问题的变体,大多数答案只是说要重构你的代码或使用async = false。

问题是,你有一个想要循环的数据数组并在每个元素上实现一些异步函数,但是你不希望一次运行多个异步线程。这可能会像数组顺序一样搞乱,或者与项目想要做的事情完全不一致。

如,

$.each(my_data,function(i,o){
  $.getJSON(o,function(r){
     //do somethin' with r then move on to next my_data element
  });
});

1 个答案:

答案 0 :(得分:2)

这是我用来解决上述问题的一小段,纯粹使用回调(没有告诉JS挂起)。它可能存在于其他地方,似乎已经足够已经存在,但我还没有看到它。所以这里希望它可以帮助你们中的一些人。

如果您希望我改进语法或以某种方式对其进行优化,请评论答案,我不是世界上最优雅的编码器。

function asyncloop(i,arr,each_cb,end_cb){
    var cont,s;
    //just do a quick check to ensure this is an array or not at end
    if ($.isArray(arr)) { 
          s = arr[i];
          if ((i+1) < arr.length) { cont = true; } else { cont = false; }
    } else {
        s= arr;
        cont = false;
    }
    each_cb(s,function(){
        if (cont == true) {
            asyncloop((i+1),arr,each_cb,end_cb);
        } else {
            end_cb();   
        }
    });
}

使用 -

进行呼叫
asyncloop(0,my_data,function(o,callback){
  //gets called with each element
  some_asynch_function(o,function(r){
    //blah blah blah
    callback();
  });
},function(){
  //finish with this
  alert('process is finished wowowow');
});

干杯!