我需要一种检查某些mysql连接的方法。
我该如何等待连接才能返回函数?
function _testConnection( _host, _user, _password, _database) {
let status = false;
let connection = mysql.createConnection({
host : _host,
user : _user,
password : _password,
database : _database
});
connection.connect((err) => {
status = !err;
connection.destroy();
});
// How to wait here for the connection?
return status;
}
答案 0 :(得分:1)
您可以创建一个Promise并从中获得返回值
function _testConnection( _host, _user, _password, _database) {
return new Promise((resolve, reject) => {
let status = false;
let connection = mysql.createConnection({
host: _host,
user: _user,
password: _password,
database: _database
});
connection.connect((err) => {
status = !err;
connection.destroy();
resolve(status)
});
})
}
您可以调用此函数
_testConnection(...).then(status => {
console.log(status)
})