【问题标题】:How to capture database connection state or ping connection?如何捕获数据库连接状态或 ping 连接?
【发布时间】:2014-12-26 14:23:04
【问题描述】:

在 Node.js 中使用 MySql driver,这是我的 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");
}

显然,这个 node-mysql 库没有原生的 Ping 方法。我认为这会很好地代替它。但是,我在控制台中看到以下问题:

调试器监听端口 53213
连接:断开
12 月 26 日星期五 2014 年 14:12:38 GMT RazorJS Express 服务器侦听端口 3000
连接已验证:true
连接为 id 17

似乎在连接实际打开之前正在记录连接状态并返回 false。也许这是异步执行的?我怎样才能让它同步运行?

【问题讨论】:

    标签: javascript mysql node.js express


    【解决方案1】:

    您已经在 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");
        });
    }
    

    【讨论】:

    • 我现在明白了......回调是我们处理异步方法返回的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 2020-04-05
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    相关资源
    最近更新 更多