Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda