0

Look at the following code :

var server = net.createServer(function(socket) {
    //Code block A


    socket.on('connect', function() {
        //Code block B
    })

    socket.on('data' , function (data){
           //Code C     

    });

});

Is there a chance code block A will be executed and code block B won't and vice versa? And if so, in what cases?

For counter example : Once code A has been executed Code C can run multiply time, without Code A ever running again.

0

3 Answers 3

2

Well, providing you call .listen(), I think you'll find that You get an order of:

(Client connects) // "connect" event fires
   |
   v 
  [A]--*-----.  // This is the Socket's "connect" event firing.
       |     |  // B and C are bound to their respective events.
       |     |
       |     |
      [B] <--.  // Binds handler to "connection" event, but 
       |        // connection event fires instantly
       |
      [C] <--.  // "data" event is fired
             |
(Client sends data)

Furthermore, A will never begin execution after B as the socket reference that B is bound to is located within the scope of closure A.

@Joe, I also think this sounds interview'y, but what the hey!

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

3 Comments

I don't understand you scheme. From what i understand code B will run every time code A will run. True?
Indeed, the function passed into net.createServer is registered as the handler for the server's 'connect' event.
See my edited post for a little more clarity, refixing the diagram as I write this.
1

This smells a bit like an interview-type question but...

1) Neither A or B will run because there's no server.listen to make it start listening.

2) If you call .listen then A will run (if the .listen was successful) but B will not run until a client connects to the server. On a connection, A will run, then B (assuming a successful connection).

2 Comments

Not an interview, just curious.
And you are wrong.When you start to listen code A will not be executed.
0

If code in block B is executed, then code in block A must have been executed.

1 Comment

Code c can run multiply times after code A has been executed once.

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.