-1

I have this code in Node.JS:

var mysql= require('mysql');

function first(){
var connection = mysql.createConnection({
  host     : 'xxxxx',
  user     : 'admin',
  password : 'xxxxx',
  database : 'xxxxx', 
  port     : 'xxxxx'
});

connection.connect();
connection.query('select*from test', function (error, results, fields) {
if (error) throw error;
  return results[0].num;
  });
}

function two(){
res = first();
console.log(res);
}

two();

I need get the response but, in the console show Undefinied. How can I fix that?

Isaac Alejandro
  • 247
  • 1
  • 3
  • 8
  • This may help. https://stackoverflow.com/questions/54346143/catch-mysql-errors-before-sending-http-response/54347539#54347539 Your `first` function returns before the query completes. – O. Jones Jan 29 '19 at 18:57
  • 1
    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) – Evert Jan 29 '19 at 19:18

1 Answers1

0
var mysql= require('mysql');
function first(){
return new Promise((resolve, reject) => {
var connection = mysql.createConnection({
  host     : 'xxxxx',
  user     : 'admin',
  password : 'xxxxx',
  database : 'xxxxx', 
  port     : 'xxxxx'
});
connection.connect();
connection.query('select*from test', function (error, results, fields) {
if (error) reject(error);
else
  resolve(results[0].num);
  });
});
}
function two(){
first().then((result) =>{
console.log(res);
}).catch((error) =>{
console.log(error);
});
}
two();

The above code should work. You code displays undefined because you sql query is sending a callback and you are console.logging it before the action is completed. I have used promise but you can also use asyc/await functionality. Promises are an elegant way of coding callback functions and it will help you to avoid callback hell when too many callbacks are involved.

Walter
  • 80
  • 5