0

I wrote a class "DBConnection" to connect to a mariadb database and query table value as below with a js file to verify return result. However, I got "undefined" on console. I expect the return is value of the sql query . Anyone knows what's going wrong and how to fix it, please!

class DBConnection { 
  constructor() {}

  static connectDb() { 
    const mariadb = require('mariadb');
    const pool = mariadb.createConnection({
        host: '127.0.0.1', 
        user:'***', 
        password: '***',
        database: 'xxx',
        connectionLimit: 5
    });
    return pool; 
  }

queryTable(sql) { 
    const dbConnection = DBConnection.connectDb(); 
    let result; 
    dbConnection.then(conn => {    
              conn.query(sql) 
              .then((rows) => {
                result = rows[0];
                conn.end(); 
                return result;
              })
              .catch(err => {
                console.log("Failed to query. \n" + err); 
                conn.end(); 
              })

          }).catch(err => {
            console.log("Failed to connect to db. \n" + err); 
          });

  }
}
module.exports = DBConnection;

Code to verify the class above.

var DBConnection = require('./db-connection'); 

  const sql = "SELECT * FROM abc where id=1";  
  const conn = new DBConnection(); 
  let result = conn.queryTable(sql); 

  console.log(result); 
Nosuv
  • 41
  • 3
  • You can't return a value directly from an asynchronous function. See also: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Mark Nov 20 '19 at 15:55
  • @MarkMeyer, I read the answers in the link but still have no idea how to fix the error. Could you please help give me some more hints? Thanks! – Nosuv Nov 21 '19 at 02:23
  • @MarkMeyer - Which function is asynchronous in the OP's code? – Rick James Nov 23 '19 at 21:45
  • @RickJames `dbConnection` clearly returns a promise as does `conn.query()`. The OP is trying to return the resolved value of these promises from `queryTable()`. This, of course, won't work because `queryTable()` will return before either of these other functions have a result. – Mark Nov 23 '19 at 21:57
  • Thanks guys for your comments. I have resolved the problem with asyn/await. You're right @MarkMeyer – Nosuv Nov 25 '19 at 03:42

0 Answers0