RethinkDB node.js驱动程序无法正确初始化全局连接variables
遇到一个非常奇怪的问题,可能是特定于我的IDE,WebStorm,因为我不能在terminal执行通过节点时再现此问题。 在下面的示例中:
r = require('rethinkdb'); var connection = null; r.connect({host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; connection = conn; }); console.log(connection);
当我尝试在callback之外logging结果时,我的连接全局variables是“null”。 不过,当我从callback中logging对象时,
var connection = null; r.connect({host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; connection = conn; console.log(connection); });
我显示一个连接JSON对象。 这似乎是一个简单的范围问题,我似乎无法弄清楚。
这是一个预期的行为。
Node.js使用JavaScript,因此以asynchronous的方式运行你的代码。
你的第一个片段发生了什么?
- r被启动
- 您尝试打开一个连接
- 打印连接
- 在某个时间点之后,连接将从您的callback中分配给conn