這裏有一個小片段我用得到解決上述問題,單純使用回調(不告訴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');
});
乾杯呢!
來源
2012-06-15 10:58:50
Dan