Question

Running into a very odd issue that may be specific to my IDE, WebStorm, as I cannot reproduce this when executing via node in the terminal. In sample below:

r = require('rethinkdb');

var connection = null;
r.connect({host: 'localhost', port: 28015}, function(err, conn) {
    if (err) throw err;
    connection = conn;
});

console.log(connection);

my connection global variable is "null" when I try to log the result outside of the callback. However when I log the object from within the callback as such:

var connection = null;
r.connect({host: 'localhost', port: 28015}, function(err, conn) {
    if (err) throw err;
    connection = conn;
    console.log(connection);
});

I show a connection JSON object. This seems like a simple scoping issue that I can't seem to figure out.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top