Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly return a result from mysql with Node?

Tags:

In the code

var stuff_i_want = ''; stuff_i_want = get_info(parm); 

And the function get_info:

get_info(data){       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             console.log(stuff_i_want); // Yep. Value assigned..     } 

in the larger scope

stuff_i_want = null 

What am i missing regarding returning mysql data and assigning it to a variable?

============ New code per Alex suggestion

var parent_id = '';     get_info(data, cb){           var sql = "SELECT a from b where info = data"           connection.query(sql, function(err, results){                 if (err){                    throw err;                 }                 return cb(results[0].objid);  // Scope is larger than function     } 

==== New Code in Use

 get_data(parent_recording, function(result){      parent_id = result;     console.log("Parent ID: " + parent_id); // Data is delivered   }); 

However

console.log("Parent ID: " + parent_id); 

In the scope outside the function parent_id is null

like image 201
Ken Ingram Avatar asked Aug 07 '15 10:08

Ken Ingram


People also ask

How do I handle MySQL errors in node JS?

createConnection(function(err, connection) { if (err) { console. log(err); res. send({ success: false, message: 'database error', error: err }); return; } connection. on('error', function(err) { console.


2 Answers

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#

like image 90
Alex Avatar answered Sep 22 '22 03:09

Alex


I guess what you really want to do here is returning a Promise object with the results. This way you can deal with the async operation of retrieving data from the DBMS: when you have the results, you make use of the Promise resolve function to somehow "return the value" / "resolve the promise".

Here's an example:

getEmployeeNames = function(){   return new Promise(function(resolve, reject){     connection.query(         "SELECT Name, Surname FROM Employee",          function(err, rows){                                                             if(rows === undefined){                 reject(new Error("Error rows is undefined"));             }else{                 resolve(rows);             }         }     )} )} 

On the caller side, you use the then function to manage fulfillment, and the catch function to manage rejection.

Here's an example that makes use of the code above:

getEmployeeNames() .then(function(results){   render(results) }) .catch(function(err){   console.log("Promise rejection error: "+err); }) 

At this point you can set up the view for your results (which are indeed returned as an array of objects):

render = function(results){ for (var i in results) console.log(results[i].Name) } 

Edit I'm adding a basic example on how to return HTML content with the results, which is a more typical scenario for Node. Just use the then function of the promise to set the HTTP response, and open your browser at http://localhost:3001

require('http').createServer( function(req, res){ if(req.method == 'GET'){     if(req.url == '/'){         res.setHeader('Content-type', 'text/html');         getEmployeeNames()         .then(function(results){           html = "<h2>"+results.length+" employees found</h2>"           html += "<ul>"           for (var i in results) html += "<li>" + results[i].Name + " " +results[i].Surname + "</li>";           html += "</ul>"           res.end(html);         })         .catch(function(err){           console.log("Promise rejection error: "+err);           res.end("<h1>ERROR</h1>")         })     } } }).listen(3001) 
like image 23
gtugnolo Avatar answered Sep 18 '22 03:09

gtugnolo