Hurricane Development Hurricane Development - 4 months ago 17
Node.js Question

make asynchronous functions within for loop run in series

So in Node.js let's say I have the following code:

for (var i = 0; i < 1000; i++) {
someAsynchronousFunction(function(err,res) {
// Do a bunch of stuff
callback(null,res);
});
}


But I want this to run synchronously. I know this is not advised in Node JS, but I am just trying to understand the language. I tried implementing the following solution, but it just ends up hanging during runtime:

for (var i = 0; i < 1000; i++) {
var going = true;
someAsynchronousFunction(function(err,res) {
// Do a bunch of stuff
callback(null,res);
going = false;
});
while (going) {

}
}


What is going wrong and what is the correct way to do this?

Answer

One of the best way to do that is to use the async library.

async.timesSeries(1000, function(n, next){
    someAsynchronousFunction(next);
});

Or you can do that with async.series() function. An example is available here : Series : independent mono-tasking

.times() documentation : http://caolan.github.io/async/docs.html#.timesSeries

Comments