Asynchronous for cycle in JavaScript

2018-12-31 11:56发布

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

for ( /* ... */ ) {

  someFunction(param1, praram2, function(result) {

    // Okay, for cycle could continue

  })

}

alert("For cycle ended");

How could I do this? Do you have any ideas?

标签: javascript
13条回答
人间绝色
2楼-- · 2018-12-31 12:13

A cleaner alternative to what @Ivo has suggested would be an Asynchronous Method Queue, assuming that you only need to make one async call for the collection.

(See this post by Dustin Diaz for a more detailed explanation)

function Queue() {
  this._methods = [];
  this._response = null;
  this._flushed = false;
}

(function(Q){

  Q.add = function (fn) {
    if (this._flushed) fn(this._response);
    else this._methods.push(fn);
  }

  Q.flush = function (response) {
    if (this._flushed) return;
    this._response = response;
    while (this._methods[0]) {
      this._methods.shift()(response);
    }
    this._flushed = true;
  }

})(Queue.prototype);

You simply create a new instance of Queue, add the callbacks you need, and then flush the queue with the async response.

var queue = new Queue();

queue.add(function(results){
  for (var result in results) {
    // normal loop operation here
  }
});

someFunction(param1, param2, function(results) {
  queue.flush(results);
}

An added benefit of this pattern is that you can add multiple functions to the queue instead of just one.

If you have an object which contains iterator functions, you can add support for this queue behind the scenes and write code which looks synchronous, but isn't:

MyClass.each(function(result){ ... })

simply write each to put the anonymous function into the queue instead of executing it immediately, and then flush the queue when your async call is complete. This is a very simple and powerful design pattern.

P.S. If you're using jQuery, you already have an async method queue at your disposal called jQuery.Deferred.

查看更多
路过你的时光
3楼-- · 2018-12-31 12:14

I needed to call some asynchronous function X times, each iteration must have happened after the previous one was done, so I wrote a litte library that can be used like this:

// https://codepen.io/anon/pen/MOvxaX?editors=0012
var loop = AsyncLoop(function(iteration, value){
  console.log("Loop called with iteration and value set to: ", iteration, value);

  var random = Math.random()*500;

  if(random < 200)
    return false;

  return new Promise(function(resolve){
    setTimeout(resolve.bind(null, random), random);
  });
})
.finished(function(){
  console.log("Loop has ended");
});

Each time user defined loop function is called, it has two arguments, iteration index and previous call return value.

This is an example of output:

"Loop called with iteration and value set to: " 0 null
"Loop called with iteration and value set to: " 1 496.4137048207333
"Loop called with iteration and value set to: " 2 259.6020382449663
"Loop called with iteration and value set to: " 3 485.5400568702862
"Loop has ended"
查看更多
宁负流年不负卿
4楼-- · 2018-12-31 12:17

Also look at this splendid library caolan / async. Your for loop can easily be accomplished using mapSeries or series.

I could post some sample code if your example had more details in it.

查看更多
梦该遗忘
5楼-- · 2018-12-31 12:18

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/

查看更多
步步皆殇っ
6楼-- · 2018-12-31 12:19

http://cuzztuts.blogspot.ro/2011/12/js-async-for-very-cool.html

EDIT:

link from github: https://github.com/cuzzea/lib_repo/blob/master/cuzzea/js/functions/core/async_for.js

function async_for_each(object,settings){
var l=object.length;
    settings.limit = settings.limit || Math.round(l/100);
    settings.start = settings.start || 0;
    settings.timeout = settings.timeout || 1;
    for(var i=settings.start;i<l;i++){
        if(i-settings.start>=settings.limit){
            setTimeout(function(){
                settings.start = i;
                async_for_each(object,settings)
            },settings.timeout);
            settings.limit_callback ? settings.limit_callback(i,l) : null;
            return false;
        }else{
            settings.cbk ? settings.cbk(i,object[i]) : null;
        }
    }
    settings.end_cbk?settings.end_cbk():null;
    return true;
}

This function allows you to to create a percent break in the for loop using settings.limit. The limit property is just a integer, but when set as array.length * 0.1, this will make the settings.limit_callback to be called every 10%.

/*
 * params:
 *  object:         the array to parse
 *  settings_object:
 *      cbk:            function to call whenwhen object is found in array
 *                          params: i,object[i]
 *      limit_calback:  function to call when limit is reached
 *                          params: i, object_length
 *      end_cbk:        function to call when loop is finished
 *                          params: none
 *      limit:          number of iteration before breacking the for loop
 *                          default: object.length/100
 *      timeout:        time until start of the for loop(ms)
 *                          default: 1
 *      start:          the index from where to start the for loop
 *                          default: 0
 */

exemple:

var a = [];
a.length = 1000;
async_for_each(a,{
    limit_callback:function(i,l){console.log("loading %s/%s - %s%",i,l,Math.round(i*100/l))}
});
查看更多
孤独寂梦人
7楼-- · 2018-12-31 12:24

We can also use help of jquery.Deferred. in this case asyncLoop function would look like this:

asyncLoop = function(array, callback) {
  var nextElement, thisIteration;
  if (array.length > 0) nextElement = array.pop();
  thisIteration = callback(nextElement);
  $.when(thisIteration).done(function(response) {
    // here we can check value of response in order to break or whatever
    if (array.length > 0) asyncLoop(array, collection, callback);
  });
};

the callback function will look like this:

addEntry = function(newEntry) {
  var deferred, duplicateEntry;
  // on the next line we can perform some check, which may cause async response.
  duplicateEntry = someCheckHere();
  if (duplicateEntry === true) {
    deferred = $.Deferred();
    // here we launch some other function (e.g. $.ajax or popup window) 
    // which based on result must call deferred.resolve([opt args - response])
    // when deferred.resolve is called "asyncLoop" will start new iteration
    // example function:
    exampleFunction(duplicateEntry, deferred);
    return deferred;
  } else {
    return someActionIfNotDuplicate();
  }
};

example function that resolves deferred:

function exampleFunction(entry, deffered){
  openModal({
    title: "what should we do with duplicate"
    options: [
       {name:"Replace", action: function(){replace(entry);deffered.resolve(replace:true)}},
       {name: "Keep Existing", action: function(){deffered.resolve(replace:false)}}
    ]
  })
}
查看更多
登录 后发表回答