user2675699
user2675699

Reputation:

RethinkDB node.js driver not correctly initializing global connection variable

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.

Upvotes: 2

Views: 683

Answers (1)

neumino
neumino

Reputation: 4353

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

Upvotes: 3

Related Questions