Why can we call socket.write immediately after net.createConnection?

I'm learning nodejs "net" module.

Why can we call socket.write("hello") immediately after socket = net.createConnection(PORT, () => {console.log("connected")}. Why needn't we wait until the connection is established, that is, why needn't we put socket.write into the callback function of net.createConnection? Can we write data to a socket when it's not connected?

Upvotes: 0

Views: 215

Answers (1)

MinusFour
MinusFour

Reputation: 14423

why needn't we put socket.write into the callback function of net.createConnection?

You could but just because socket.write doesn't throw any errors doesn't mean it's writing the data right then. If you look at the documentation for socket.write you'll see:

The optional callback parameter will be executed when the data is finally written out, which may not be immediately.

It's still a good practice to use that parameter or use the connect event depending on what other logic you'd want to use.

Upvotes: 1

Related Questions