2014-12-26 53 views
0

使用MySql driver对Node.js的,这里是我的ping方法:如何捕获数据库连接状态或ping连接?

function ping(){ 
    connection.connect(function(err) { 
    if (err) { 
     console.error('error connecting: ' + err.stack); 
     return false; 
    } 

    console.log('connection authenticated: ' + (connection.state == "authenticated")); 
    console.log('connected as id ' + connection.threadId); 
    }); 

    console.log("connection: " + connection.state); 
    return (connection.state == "authenticated"); 
} 

显然,这个节点的mysql库没有一个本地Ping方法。我认为这将取而代之。但是,我看到了以下问题在控制台:

调试端口监听53213
连接:断开
周五,12月26日 2014 14点12分38秒GMT RazorJS Express服务器侦听端口3000
连接验证:真
连接作为ID 17

看来,连接状态被记录并返回false之前的连接实际上是开放的。也许这是正在执行异步?我如何获得这个同步功能?

回答

0

你已经在connection.connect函数的回调之外编写了下面的代码。因此,在你的connection.connect执行它的回调之前,下面的代码被执行(node.js的异步性质),因此它的第一个安慰为断开连接。

console.log("connection: " + connection.state); 
    return (connection.state == "authenticated"); 

上面应该在回调中。

function ping() { 
    connection.connect(function(err) { 
     if (err) { 
      console.error('error connecting: ' + err.stack); 
      return false; 
     } 
     console.log('connection authenticated: ' + (connection.state == "authenticated")); 
     console.log('connected as id ' + connection.threadId); 
     console.log("connection: " + connection.state); 
     return (connection.state == "authenticated"); 
    }); 
} 
+0

我现在明白了......回调是我们如何处理来自异步方法的回报。 – IAbstract