1

I'm retrieving data from mysql db and I need to send data to render in my ejs file.

router.get('/', function(req, res, next) {
  res.render('index',  { speedAccelData: getSpeedAccelData() });
});

module.exports = router;

Following is the function which I used to get data from database. It successfully prints jsonStr with required data. I need to return jsonStr from the function.

var getSpeedAccelData = function () {

  var jsonStr;

  var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    database: "db_name"
  });

  con.connect(function(err){
    if(err){
      console.log('Error connecting to Db');
      return;
    }
  });

  con.query('SELECT * FROM table_name',function(err, result){
    if(err) throw err;
    jsonStr = JSON.stringify(result)
    console.log(jsonStr);
  });
  con.end();

};

How can I return query data to render?

2
  • it's asynchronous, you can't return a value like this. One solution is to pass a callback to your getSpeedAccelData function. Or you can return a Promise in your getSpeedAccelData function Commented Aug 11, 2016 at 8:47
  • Possible duplicate of How do I return the response from an asynchronous call? Commented Aug 11, 2016 at 9:31

1 Answer 1

3

You can use Promise to achieve this

var getSpeedAccelData = function () {

  var promise = new Promise(function (resolve, reject) {

    var jsonStr;

    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "root",
      database: "db_name"
    });

    con.connect(function(err){
      if(err){
        console.log('Error connecting to Db');
        reject();
      }
    });

    con.query('SELECT * FROM table_name',function(err, result){
      if(err) {
        reject(err);
      } else {
        jsonStr = JSON.stringify(result)
        resolve(jsonStr);
      }

    });

    con.end();

  });

  return promise;
};

Then in your controller you can proceed like this :

router.get('/', function(req, res, next) {
  getSpeedAccelData()
  .then(function success(result) {
     res.render('index',  { speedAccelData: result });
  }, function error(error) {
     ...
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.