简体   繁体   中英

How to use responses from MySQL in one function with Node.JS?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM