1

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?

4
  • Why wouldn't node wait ? Is your loop so long it could trigger a timeout ? Commented May 4, 2013 at 19:00
  • yes it will wait, user a different process if it's gonna take forever... Commented May 4, 2013 at 19:01
  • Hmmm, did you even try? Commented May 4, 2013 at 19:02
  • @LeeTaylor Yes, I tried. It seemed to me like the entire main thread is waiting Commented May 5, 2013 at 1:52

2 Answers 2

2

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.

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

Comments

0

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

4 Comments

+1 async module - don't loop, try map/reduce or recursion, but not looping. Map lok like it would work for you
You can't say "don't loop" without knowing what's inside the loop. Loop aren't forbidden in node.
I agree with both @dystroy that it is not forbidden to use loops, however since node is asynchronous loops tend to get ugly while running and can give unexpected results if not used properly, hence the modules like async are very helpful
@dystroy, I was probably a bit quick on the "don't loop" trigger, but my assumption is that he needs to block in the loop, and then things go south from there. I'm no master, been using node about 4 months.

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.