0

I'm a C/C++ guy trying to make a simple web app using Node.js, Express.js and MariaDB.

function getData(sensor)
{
  var query = c.query('SELECT * FROM sensor_data WHERE id >= ALL (SELECT id FROM sensor_data WHERE sensor = ?) AND sensor = ?', [sensor,sensor]);
  query.on('result', function(res) {
    res.on('data',function(row) {
      return(row);
    });
  });
}

app.get('/', function(req, res) {
  res.render('index', {
    temperatureSala: getData('sala').temperature + 'ºC',
    humiditySala: getData('sala').humidity + '%'
  });
});

My problem is dealing with the asynchrony. When I try to render the page the render functions finishes running first and then I get that the variables are undefined. The query finishes after and the result is correct.

What is the best way of dealing with this? Any question you have please ask.

Thank you!

MAntunes
  • 101
  • 1
  • 1
  • 5
  • Pass a "callback" to getData (just as used in `on`) or use promises, etc. `return(row)` is meaningless 1) it only applies to the *innermost* function 2) it occurs *after* the top-level function returns. – user2864740 Jul 01 '18 at 21:45
  • ref: `function getData(sensor, functionToCallWithData) { .. }` .. `getData('sala', function (data) { res.render.. }` .. – user2864740 Jul 01 '18 at 21:46
  • Possible duplicate of [Dealing with NodeJS asynchronous behavior](https://stackoverflow.com/questions/15692946/dealing-with-nodejs-asynchronous-behavior) – Paul Jul 01 '18 at 22:15
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Kyll Jul 01 '18 at 22:19

1 Answers1

0

You should structure your app.get like this. I have omitted your function getData but if you need it for later use then you can set it up in such a way that it takes a callback and execute res.render inside of that callback.

app.get('/', function(req, res) {
  const query = c.query('SELECT * FROM sensor_data WHERE id >= ALL (SELECT id FROM sensor_data WHERE sensor = ?) AND sensor = ?', ['sala', 'sala']);

  query.on('result', function(queryRes) {
    queryRes.on('data',function(row) {
      const temperatureSala = row.temperature + 'ºC',
            humiditySala = row.humidity + '%';

      res.render('index', {
        temperatureSala,
        humiditySala
      });
    });
  });
});
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
  • 1
    Careful with shadowing `res` in your function. Does `res` point to the the function argument or express's response object? – Mark Jul 01 '18 at 22:05