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?
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)
You simply create a new instance of
Queue
, add the callbacks you need, and then flush the queue with the async response.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:
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.
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: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:
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.
I simplified this:
FUNCTION:
USAGE:
EXAMPLE: http://jsfiddle.net/NXTv7/8/
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
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%.
exemple:
We can also use help of jquery.Deferred. in this case asyncLoop function would look like this:
the callback function will look like this:
example function that resolves deferred: