如何等待连接

时间:2019-07-27 11:42:01

标签: javascript vue.js electron

我需要一种检查某些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;
}

1 个答案:

答案 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)
})