How to properly return a result from mysql with Node?

You’re going to need to get your head around asynchronous calls and callbacks with javascript, this isn’t C#, PHP, etc…

Here’s an example using your code:

function get_info(data, callback){
      
      var sql = "SELECT a from b where info = data";

      connection.query(sql, function(err, results){
            if (err){ 
              throw err;
            }
            console.log(results[0].objid); // good
            stuff_i_want = results[0].objid;  // Scope is larger than function

            return callback(results[0].objid);
    })
}


//usage

var stuff_i_want="";

 get_info(parm, function(result){
    stuff_i_want = result;

    //rest of your code goes in here
 });

When you call get_info this, in turn, calls connection.query, which takes a callback (that’s what function(err, results) is
The scope is then passed to this callback, and so on.

Welcome to javascript callback hell…

It’s easy when you get the hang of it, just takes a bit of getting used to, coming from something like C#

Leave a Comment