Reputation: 2039
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.
Upvotes: 0
Views: 300
Reputation: 42666
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 On a connection, A will run, then B (assuming a successful connection)..listen
then A will run (if the .listen was successful) but B will not run until a client connects to the server.
Upvotes: 1
Reputation: 364
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!
Upvotes: 2
Reputation: 10346
If code in block B is executed, then code in block A must have been executed.
Upvotes: 0