0

I am using mysql with Electron. Here is my code to connect to database. I am in a problem of variable scope. I do google for a long time but found no solution.

What I want to do is described within the uppercase comment inside the code. Please look at the code and give me suggestion if any.

<script>
var mysql = require('mysql');
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: null,
  database: 'electron_db'
});

connection.connect();
var sql = 'SELECT `emp_id`,`emp_name` FROM `employee`';
connection.query(sql, function(error, results, fields) {
  if (error) console.log(error.code);
  else {
    console.log(results);
    $('#resultDiv').text(results[0].emp_name); //emp_name is column name in    your database

    // I WANT TO ASSIGN emp_name TO A VARIABLE x AND TO USE IT OUTSIDE THE CALLBACK.
    // LIKE THIS
    // ASSIGN VARIABLE HERE

    x = results[0].emp_name;

  }
});
connection.end();

// USE VARIABLE x HERE
$('#resultDiv').text(x);

</script> 
t.niese
  • 39,256
  • 9
  • 74
  • 101
Md. Harun Or Rashid
  • 2,000
  • 4
  • 21
  • 37
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – t.niese Oct 10 '17 at 16:37
  • It is not a scoping problem. The problem is that `connection.query` is async and as of that `$('#resultDiv').text(x);` is executed before the callback of the query is executed. One way to solve it is to move `$('#resultDiv').text(x);` inside of the query callback. – t.niese Oct 10 '17 at 16:38

0 Answers0