user225269
user225269

Reputation: 10893

How to return results from node mysql

How to return results from node mysql https://github.com/felixge/node-mysql I'm trying to access the results returned outside of the function.

var mysql = require('mysql');
var TEST_DATABASE = 'zenoir';
var TEST_TABLE = 'tbl_sessions';
var client = mysql.createClient({
  user: 'root',
  password: 'secret',
});

var outer = 20;
client.query('USE '+TEST_DATABASE);

client.query(
  'SELECT ses_title FROM '+TEST_TABLE,
  function selectCb(err, results, fields) {
    if (err) {
      throw err;
    }


    var boom  = results;
    var rooms = [];
    var index = 0;
    var name = 'session';

    for(var b in boom){
         rooms[b] = {};
         rooms[b][name + index] = boom[b]['ses_title'];
         index += 1;
    }

    var exe = {};
for(var mon in rooms){
 for(var zeb in rooms[mon]){
    exe[mon] = rooms[mon][zeb];
 }

}


    outer = exe; //I want to access the exe variable outside the function scope

    client.end();
  }
);

console.log(outer); //I still get the initial value 20 in here.

Upvotes: 1

Views: 951

Answers (1)

Shikiryu
Shikiryu

Reputation: 10219

Well, as you can see here, query() can be use with those params :

  • SQL query, SQL query param, callback on completion
  • SQL query, callback on completion

You are using the 2nd one.

Callback function is active only when the query is done (which means, it can take time). Javascript doesn't stop on your query and continue with the script ( console.log(outer); ) and when your query is done then it apply the callback function and change outer.

Upvotes: 3

Related Questions