Javascript 如何捕获数据库连接状态或ping连接?
使用for Node.js,以下是我的ping方法: 显然,这个节点mysql库没有本机Ping方法。我认为这会很好地代替它。但是,我在控制台中看到以下问题: 在端口53213上侦听的调试器 连接:断开 12月26日,星期五 2014 14:12:38 GMT RazorJS Express服务器在端口3000上侦听 已验证的连接:true 以id 17连接Javascript 如何捕获数据库连接状态或ping连接?,javascript,mysql,node.js,express,Javascript,Mysql,Node.js,Express,使用for Node.js,以下是我的ping方法: 显然,这个节点mysql库没有本机Ping方法。我认为这会很好地代替它。但是,我在控制台中看到以下问题: 在端口53213上侦听的调试器 连接:断开 12月26日,星期五 2014 14:12:38 GMT RazorJS Express服务器在端口3000上侦听 已验证的连接:true 以id 17连接 在连接实际打开之前,似乎正在记录连接状态并返回false。也许这是异步执行的?如何使其同步运行?您在connection.connect函
在连接实际打开之前,似乎正在记录连接状态并返回false。也许这是异步执行的?如何使其同步运行?您在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");
});
}
我现在明白了…回调是我们处理异步方法返回的方式。
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");
});
}