codejammer
codejammer

Reputation: 469

looping in a node.js callback function

Can I run a loop (while, for, dowhile etc) in a callback function. Here is a sample code :

var execute = function (data,callback) 
{
    //do something with data
    callback();
}

execute (data,function(error,returnDataArray)
{
    var boo = true;
    while(boo)
    {
        //do something with returnDataArray
        if (returnDataArray.length == 10) 
            boo=false;
    }
});

Now, my doubt is, does the main node.js thread wait until the above while loop is executed?

Upvotes: 1

Views: 220

Answers (2)

Simon Boudrias
Simon Boudrias

Reputation: 44589

Your main thread will be blocked by the looping occuring inside a callback function. That's because callback functions are just delayed until completion, and then, they're pushed into the JavaScript event loop and executed once the thread is free. In simpler word, everything in node (and JavaScript) happen in a single thread (normal execution, callback, timeouts, etc).

The only way to execute a function into another thread with JavaScript is manually pushing it into another thread. In browser that'll be a web worker, and on node a cluster.

Upvotes: 2

V31
V31

Reputation: 7666

You can have something like this

var execute = function (data,function(error,returnDataArray)
{
  //do something with data
  var boo = true;
  while(boo)
  {
    //do something with returnDataArray
    if (returnDataArray.length == 10) 
        boo=false;
  }
});

or you can use the async module, using function async.parallel

Upvotes: 0

Related Questions