0

There are many variants of this question on Stack, most answers just saying to restructure your code or use async = false.

The question again is, you have an array of data you want to loop through and enact some asynchronous function on each element, but you don't want multiple asynch threads running at once. This could mess things up like array order or be completely at odds with what your project wants to do.

e.g.,

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

1 Answer 1

2

Here's a little snippet I use to get around the above problem, purely using callbacks (no telling JS to hang). It may exist elsewhere, seems handy enough to already exist, but I haven't seen it. So here's hoping it helps some of you.

Please comment on the answer if you want me to improve my syntax or optimise it somehow, I'm not the most elegant coder in the world.

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

Call using --

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

Cheers then!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.