Asynchronous for cycle in JavaScript

前端 未结 13 1102
温柔的废话
温柔的废话 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 + ' <br>');
                loop();
            },1000);
        },
        callback : function(){
            document.write('All done!');
        }    
    });
    

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

    0 讨论(0)
提交回复
热议问题