1

I'm testing with node.js with express.

Theoretically, If I run something very heavy calculation on a "for loop" without any callbacks,

it is blocked and other request should be ignored.

But In my case, regular "for loop"

for(var i=0;i<300000;i++) {
    console.log( i );
}

does not make any request blocks but just high cpu load.

It accepts other requests as well.

but why should I use some other methods to make these non-blocking such as

process.nextTick()

Or does node.js take care of basic loop functions ( for, while ) with wrapping them with process.nextTick() as default?

2 Answers 2

2

Node runs in a single thread with an event loop, so as you said, when your for loop is executing, no other processing will happen. The underlying operating system TCP socket may very well accept incoming connections, but if node is busy doing your looping logic then the request itself won't be processed until afterward.

If you absolutely must run some long-running processin Node, then you should use separate worker processes to do the calculation, and leave the main event loop to do request handling.

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

2 Comments

what about difference between using process.nextTick in "for loop" or not using process.nextTick in "for loop"
A snippet would help me better answer, but basically without nextTick the loop runs just like in any other language. It will run until it has gone through all values of 'i', and no other processing can happen. nextTick instructs node to execute the argument function on the next time through the event loop. In theory, this means that you are queuing up your processing to run in the event loop, along with everything else. This means that there is time for other data to be processed, like incoming requests. That said, the main loop will still be doing lots of heavy processing, which can be bad.
0

Node doesn't wrap loops with process.nextTick().

It may be that your program is continuing to accept new connections because console.log is yielding control back to the main event loop; since it's an I/O operation.

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.