Home > OS >  How can I update mysql2 query to not return undefined for return?
How can I update mysql2 query to not return undefined for return?

Time:02-27

I am using nodejs and mysql2. I am storing all my queries inside a class. When I console.log the results I am able to view the data correctly, however when I use a return statment to return the data, I am getting undefined. I believe I need to use promises, but am uncertain how to do so correctly. Here is what I have currently which is returning undefined,

    viewManagerChoices() {
        const sql = `SELECT CONCAT(first_name, ' ',  last_name) AS manager, id FROM employee WHERE manager_id IS NULL`;
        db.query(sql, (err, rows) => {
        if (err) throw err;
           const managers = rows.map(manager => ({ name: manager.manager, value: manager.id }));
           managers.push({ name: 'None', value: null });
           return managers;
        });
    };

This is my attempt at using promises which is returning as Promise {<pending>},

viewManagers() {
        return new Promise((resolve, reject) => {
            const sql = `SELECT CONCAT(first_name, ' ',  last_name) AS manager FROM employee WHERE manager_id IS NULL`;
            db.query(sql,
                (error, results) => {
                    if (error) {
                        console.log('error', error);
                        reject(error);
                    }
                    const managers = [];
           for (let i = 0; i < results.length; i  ) {
               managers.push({ name: results[i].manager, value: i 1 });
           }
           managers.push({ name: "None", value: null });
                    resolve(managers);
                }
            
            )
        })
        
    }

My class is called Query and I am calling these methods by doing,

const query = new Query();
query.viewManagerChoices();
query.viewManagers();

CodePudding user response:

Your implementation for viewManagers is correct however promises don't make calls synchronous.

Either you need to use then callback or await the result in async context.

const query = new Query();
query.viewManagers().then((managers) => {
  // do stuff here
}).catch((error) => console.error(error.message));

or

async someFunc() {
  const query = new Query();
  try{
    const managers = await query.viewManagers();
  }catch(error){
    console.error(error.message);
  }
}

CodePudding user response:

use MySQL it's more easier for handling errors and data

  • Related