How to save the result of MySql query in variable using node-mysql

You can't do that because network i/o is asynchronous and non-blocking in node.js. So any logic that comes afterwards that must execute only after the query has finished, you must place inside the query's callback. If you have many nested asynchronous operations you may look into using a module such as async to help better organize your asynchronous tasks.


Well @Fadi, connection.query is async, which mean when your call your console.log(someVar), someVar has not been set yet.

What you could do:

var someVar = [];

connection.query("select * from ROOMS", function(err, rows){
  if(err) {
    throw err;
  } else {
    setValue(rows);
  }
});

function setValue(value) {
  someVar = value;
  console.log(someVar);
}

Tags:

Mysql

Node.Js