skip to Main Content

i am trying to get data from MySQL database using node.js and i need to use it on other modules so i need to send query result it seem so easy but i get stuck :

i get data using this calss and funcation:

class user{
user(){}
static async getUser(email: string) {
        let Finalresult = await DataBase.query("SELECT * FROM childcare.user where email =?", [email], function (err, result, fields) {
            if (err) return err;
            else
                return result;

        });

        return Finalresult;

    } }
module.exports = user;

i want to use data in that function and i expect to get the result of query

const userModule = require("../../modules/user");
static async login(req: Request, res: Response) {
    const { email, password } = req.body;
    const user = await userModule.getUser(email);
    console.log('user is ', user);)}

But i get
user is *<ref 1> Query

2

Answers


  1. You can’t use then/catch and async/await together. You need to remove the callback part.

    class User{
    user(){}
    async getUser(email: string) {
            try {
               let finalResult = await DataBase.query("SELECT * FROM childcare.user where email =?", [email])
               return finalResult;
            } catch(e) {
               console.log(e);
            }
            
    
        } }
    module.exports = new User();
    

    In your calling module:

    const userModule = require("../../modules/user");
    static async login(req: Request, res: Response) {
        const { email, password } = req.body;
        const user = await userModule.getUser(email);
        console.log('user is ', user)
      }
    
    
    Login or Signup to reply.
  2. The issue you’re encountering is related to the fact that you are using a callback function to handle the query result in your getUser method. The await keyword doesn’t work as expected with functions that use callbacks.

    To make your code work as expected, you can either use a Promise-based approach with util.promisify to convert the callback-based function into a Promise, or you can use a library like mysql2 which has built-in support for Promises. Here’s how you can do it using mysql2:

    First, you need to install mysql2 if you haven’t already:

    npm install mysql2
    

    Then, you can modify your getUser method as follows:

    const mysql = require('mysql2/promise'); // Import the 'mysql2' library
    
    class User {
      static async getUser(email) {
        const connection = await mysql.createConnection({
          host: 'your_host',
          user: 'your_user',
          password: 'your_password',
          database: 'your_database',
        });
    
        try {
          const [rows, fields] = await connection.execute('SELECT * FROM childcare.user WHERE email = ?', [email]);
          return rows; // This will contain your query result
        } catch (err) {
          console.error(err);
          return []; // Handle the error appropriately
        } finally {
          connection.close();
        }
      }
    }
    
    module.exports = User;
    

    Make sure to replace 'your_host', 'your_user', 'your_password', and 'your_database' with your actual MySQL database connection details.

    Now, your getUser method will return the query result as expected, and you can use it in your login function:

    const userModule = require('../../modules/user');
    
    static async login(req, res) {
      const { email, password } = req.body;
      const user = await userModule.getUser(email);
      console.log('user is ', user);
      // Rest of your login logic
    }
    

    With this setup, your code should work correctly, and you will get the actual query result in the user variable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search