0

I'm doing a monitoring system project in which I have Arduino sensors data being sent to a node.js server (thru GET requests) and then stored in a MySQL DB.

Whenvever I successfully send data to the server, it connects to the MySQL DB and queries the last 5 received records to do some processing.

Therefore, I need to store the rows of those 5 records in a variable for later use. Meaning that I have to get rows from a connection.query in a variable.

I read that the fact that I'm not able to do this is because node.js being async. So my questions are:

  1. Is it possible to do the described tasks the way I'm trying?
  2. If not, is there any other way to do so?

I'm not putting the whole code here but I'm running a separated test that also doesn't run properly. Here it is:

var mysql = require('mysql');

var con = mysql.createConnection({
      host    : "127.0.0.1",
      user    : "root",
      password: "xxxx",
      database: "mydb",
      port    : 3306
});
var queryString = "SELECT id, temp1, temp2, temp3, temp4, level_ice_bank, flow FROM tempdata ORDER BY id DESC LIMIT 5";

con.connect(function(err) {
  if (err) throw err;
});

var result_arr = [];
function setValue (value) {
  result_arr = value;
}

con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    //console.log(rows);
    setValue(rows);
  }
});

console.log(result_arr);

It logs:

[]

But if I uncomment console.log(rows); it logs what I need to store in the variable result_arr.

Thanks in advance to all.

3
  • The thread will not wait for con.query to finish. It will immediately execute the console.log(result_arr) after executing the con.query line that's why there's no value being logged because con.query is not yet finished querying. You have a result when you uncomment //console.log(rows); because con.query finished its execution. Treat it as when con.query is executed, a new thread is created to run its execution and the main thread will go on with its life even it con.query is not yet finished.
    – suguspnk
    Commented Jul 6, 2017 at 9:44
  • @suguspnk thanks for your explanation! I had understood more or less it had to be something like that. Do you know how can I make setValues(rows); happen before console.log(result_arr);?
    – arocha
    Commented Jul 6, 2017 at 9:50
  • See dan's answer. It's the correct approach for this.
    – suguspnk
    Commented Jul 6, 2017 at 9:54

1 Answer 1

3

You're seeing this behaviour because con.query(...) is an asynchronous function. That means that:

console.log(result_arr);

Runs before:

con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    //console.log(rows);
    setValue(rows);
  }
});

(Specifically, the setValue(rows) call)

To fix this in your example, you can just do:

con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    setValue(rows);
    console.log(result_arr);
  }
});

If you want to do more than just log the data, then you can call a function which depends on result_arr from the con.query callback, like this:

con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    setValue(rows);
    doCleverStuffWithData();
  }
});

function doCleverStuffWithData() {
    // Do something with result_arr
}
4
  • It's also worth mentioning that the async/await functionality can be added to the Node.js mysql module with a bit of work. This would also solve your problem. Hopefully support for this will be added natively to the mysql package in future.
    – dan
    Commented Jul 6, 2017 at 9:59
  • your explanation was perfect, it worked as I wanted and I think I can now move on with thr project. Thanks!
    – arocha
    Commented Jul 6, 2017 at 10:18
  • @AntónioRocha Great, I'm really glad it helped. The async/callback concept in JavaScript are definitely worth getting your head around early on :)
    – dan
    Commented Jul 6, 2017 at 10:35
  • @dan I'm trying to return result_arr in the doCleverStuffWithData() function but I still get "Promise Pending" message. Any ideas? Commented Dec 19, 2018 at 13:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.