Asynchronous for cycle in JavaScript

前端 未结 13 1274
温柔的废话
温柔的废话 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 11:45

    If you like wilsonpage's answer but are more accustomed to using async.js's syntax, here is a variation:

    function asyncEach(iterableList, callback, done) {
      var i = -1,
          length = iterableList.length;
    
      function loop() {
          i++;
          if (i === length) {
            done(); 
            return;
          }
          callback(iterableList[i], loop);
      } 
      loop();
    }
    
    
    asyncEach(['A', 'B', 'C'], function(item, callback) {
        setTimeout(function(){
        document.write('Iteration ' + item + ' 
    '); callback(); }, 1000); }, function() { document.write('All done!'); });

    Demo can be found here - http://jsfiddle.net/NXTv7/8/

提交回复
热议问题