Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
How can I update mysql2 query to not return undefined for return?

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();
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
  }
}

Once you use promise you cannot just get a returned value without async/await or then flag. Once it's a promise the flow continues as the original.

For example:

// This is promise too because it has async flag.
// You cannot make it sync if you use promise in it
async myFunc(){ 
  const const query = new Query();
  const managers = await query.viewManagers();

  return managers;
}
// It actually returns Promise<...>

// Now if you want to use myFunc in another function 
// You need to do it the same way again
async anotherFunc(){ 
  const something = await myFunc();

  return something; // Returns promise
}

You can read more about promises here

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda