简体   繁体   中英

Undefined when returning 'results' parameter from mysql query

Trying to send data to EJS from MySQL Databases using Node.js and Express , but it shows error when returning 'results' parameter:

function dbData(){
    connection.query('SELECT * FROM clients', (err, results, fields)=>{
        return results;
    });
}

Route:

app.get('/', (req, res)=>{
    let data = dbData(); 
    console.log(data);
});

And when going to localhost:3000 , the console shows:

不明确的

The thing is that when i console log the results:

connection.query('SELECT * FROM clientes', (err, results, fields)=>{
        console.log(results);
        return results;
    });

The console shows:

数组控制台.log

So why data is equal to 'undefined' if i'm returning the 'results' array? and how can i solve this?

I'm new in Node.js, sorry if this is too obvious:(

At first glance, the documentation for mysql - a pure node.js JavaScript Client that implements the MySQL protocol, says in its very first topics that you should not return anything from connection.query() method.

This said,

function dbData(){
    connection.query('SELECT * FROM clients', (err, results, fields)=>{
        return results;
    });
}

was supposed to be without any return (or just return; )

function dbData(){
   connection.query('SELECT * FROM clients', function (error, results, fields) {
      if (error) throw error;
      console.log('The solution is: ', results);
    });
}

So when you do console.log(data) you are actually printing undefined because it isn't supposed to return a thing. If you want to take the result out of the query, you should consider using a callback.

function dbData(callback){
   connection.query('SELECT * FROM clients', function (error, results, fields) {
      if (error) throw error;
      callback(results);
    });
}

app.get('/', (req, res)=>{
    dbData(data => {
        console.log(data);
    }); 
});

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