Asynchronous for cycle in JavaScript

前端 未结 13 1226
温柔的废话
温柔的废话 2020-11-22 11:37

I need a loop that waits for an async call before continuing. Something like:

for ( /* ... */ ) {

  someFunction(param1, praram2, function(result) {

    //         


        
13条回答
  •  迷失自我
    2020-11-22 12:06

    I simplified this:

    FUNCTION:

    var asyncLoop = function(o){
        var i=-1;
    
        var loop = function(){
            i++;
            if(i==o.length){o.callback(); return;}
            o.functionToLoop(loop, i);
        } 
        loop();//init
    }
    

    USAGE:

    asyncLoop({
        length : 5,
        functionToLoop : function(loop, i){
            setTimeout(function(){
                document.write('Iteration ' + i + ' 
    '); loop(); },1000); }, callback : function(){ document.write('All done!'); } });

    EXAMPLE: http://jsfiddle.net/NXTv7/8/

提交回复
热议问题