0

I am a beginner with node.js and I know this piece of code is asynchronous, due to the private function passed in the CreateServer method and in the socket.on method.

require('net').createServer(function (socket) {
console.log("connected");

socket.on('data', function (data) {
    console.log(data.toString());
});
})

But does it mean that when a "data" event fires, the server has to execute only the associated piece of code, or can it process also other "data" requests while it is already processing the previous 'data' request?

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • 3
    By your question I find that you're quite confused of how these kind of code behaves. You should understand fundamentally how javascript works and why does it have async execution. Mainly because it's single threaded. Take a book, however, it is going to make your codeing painless in future. – kidwon Jun 26 '14 at 10:23
  • 1
    [Try this](http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/) and [this](http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/) and [this](http://stackoverflow.com/questions/19822668/what-exactly-is-a-node-js-event-loop-tick) and [this](https://developer.yahoo.com/blogs/ydnfourblog/part-1-understanding-event-loops-writing-great-code-11401.html). – Andy Jun 26 '14 at 10:28
  • To your question, when event occurs the async code that accompanies it is going to be executed in the first opening of free resource. All other async events are going to stand in line after it waiting their turn to be executed when there are openings again. So one after another they go between the regular sync executions. – kidwon Jun 26 '14 at 10:36

1 Answers1

0

Node.js is single threaded. That means that there is no parallelism. Everything happens sequentially. If data event fires then the associated handler will fire and nothing else will run at the same time. Every block of code (i.e. code between brackets {...}) will run sequentially and nothing can interrupt it.

this piece of code is asynchronous, due to the private function passed in the CreateServer method

That's actually not true. Have a look at this example:

var fn = function(clb) {
    clb(1);
}

console.log("start");
fn(function(x) {
    console.log(x);
});
console.log("end");

fn function accepts a callback but it is not asynchronous. The function you were talking about is asynchronous because we know that it is asynchronous. There are several asynchronous functions in Node.js: process.nextTick, setTimeout, setInterval, lots of I/O function (files, network, etc.). Combination of these asynchronous functions is also asynchronous. But without knowing what a function does you can't assume a priori that it is asynchronous. The real life example of a synchronous function with a callback is .forEach method on lists.

freakish
  • 54,167
  • 9
  • 132
  • 169