This is an expected behavior.
Node.js uses JavaScript and therefore run your code in an asynchronous way.
What happens in your first snippet is that
- r is initailized
- You try to open a connection
- Print the connection
- And at some point later, connection is assigned conn from your callback