jwchang
jwchang

Reputation: 10864

Should I use for loop async way when I use node.js?

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?

Upvotes: 1

Views: 336

Answers (2)

kgilpin
kgilpin

Reputation: 2226

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.

Upvotes: 0

loganfsmyth
loganfsmyth

Reputation: 161627

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.

Upvotes: 2

Related Questions