1

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?

0

2 Answers 2

2

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.

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

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, I was actually looking for an Async function to do this, but I could not find it.
Did you mean timesSeries()? Also, form a performance standpoint on strictly asynchronous loop in parallel. Is it faster to run Async.times() or simply do the for loop?
Yes ! Because .times() run in parallel. For the faster way, I don't know. I think it must be similar, but we need some benchmarks to concluded that.
1

Another way to do this is using Promises to generate a sequential execution of them thanks to Array#reduce :

// Function that returns Promise that is fllfiled after a second.
function asyncFunc (x){
  return new Promise((rs, rj)=>{
    setTimeout( ()=>{
      console.log('Hello ', x);
      rs();
    }, 1000)
  });
}
// Generate an array filed with values : [0, 1, 2, 3, ...]
Array.from({length : 1000}, (el, i)=> i)
// loop througth the array chaining the promises.
.reduce( (promise, value) => 
   promise.then(asyncFunc.bind(null, value))
, Promise.resolve(null));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.