2

I'm pretty new to using Express.js and I have an issue returning the data from the database query. The goal is to get user info from the table as JSON inside userController but only thing I get is undefined. I tried many different things but can't get my head around how to return the value from the method.

db.js

const mysql = require('mysql2');
var con = mysql.createPool({
    //db data here
});
module.exports = con;

userController.js

var User = require("../models/userModel");
exports.registerUser = function(req, res){
    if(req.method == 'POST'){
        var username = req.body.username;
        var email = req.body.email;
        //doing checks

        var u1 = new User(username, email);
        console.log(u1.getInfo());
    }
}

userModel.js

const db = require('../config/db');
module.exports = class User{
//constructor here

  getInfo(){
    try{
       var query = "SELECT * FROM users";
        db.query(query, function(err, data){
            return JSON.stringify(data);
        });
    }
    catch(err){
        return err;
    }
 }
}
Qgruber
  • 137
  • 1
  • 11
jack12
  • 33
  • 4
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – VLAZ Sep 17 '21 at 07:29

1 Answers1

0

You are getting undefined because the query need to wait the answer, and when you call getInfo(), the return JSON.stringify(data); are only execute when the query have the data.

You can use promise warper, because you need to wait to the database response. To use promises mysql2 have this package: const mysql = require('mysql2/promise');

Make your getInfo() function asynchronous

  async getInfo(){
    try{
       const res = await db.execute('SELECT * FROM users');
       return res;
    }
    catch(err){
        return err;
    }
  }

Then you can call the function with await:

exports.registerUser = async function(req, res){
    if(req.method == 'POST'){
        var username = req.body.username;
        var email = req.body.email;
        //doing checks

        var u1 = new User(username, email);
        console.log(await u1.getInfo());
    }

I cant test the code now, but it should work

Jorge Montejo
  • 485
  • 1
  • 6
  • 17