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

585
Visualizações
nodejs function returning undefined mysql

I have a function that checks if a user is admin or not. If it finds the user id in the database table, it needs to return true, otherwise it needs to return false, but I'm getting undefined. Can you help me?

function isAdmin(useruid) {
  db.query("SELECT * FROM admins", function(err,rows,field) {
    if(!err) {
  
      rows.forEach(function(element) {
        if (useruid === element.uid) {
          console.log("[is admin] Found admins!")
          return true;

        } else {
          console.log("[is admin] User is not admin!")
          return false;
        }
      });
  
    } else {
      console.log(err);
      return false;
    }
  })
}

I added ; on the missing lines. I'm receiving output of the console.logs, but the function is still returning undefined instead of false or true.

It looks like:

function isAdmin(useruid) {
  db.query("SELECT * FROM admins", function(err,rows,field) {

    if(!err) {
      rows.forEach(function(element) {
        if (useruid === element.uid) {
          console.log("[is admin] Found admins!");
          return true;
        } else {
          console.log("[is admin] User is not admin!");
          return false;
        }
      });
  
    } else {
      console.log(err);
      return false;
    }
  })
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

As noted the solution is more complicated than you might suspect given the asynchronous nature of Node. There are several ways to address the issue your question presents but I'll include just one here that is relatively flexible and lightweight.

The good news is your function isAdmin and the query it includes can be made much simpler so you'll pick up some lines of code there.

Since you start with a UID and your goal is only to check that it exists in the table, you can use a targeted query and skip all the result looping. This will save time and resources in Node as well as MySQL.

Updated Function Note this is now an async function with a Promise. This way we can later call and await the results. Also the db.query takes an argument for the ? placeholder. We pass it our useruid variable.

const isAdmin = async (useruid) => {
  return new Promise((resolve, reject) => {
    db.query('SELECT uid FROM admins WHERE uid = ?;', useruid, function (error, results, fields) {
      if (error) reject(error);

      // when we get our results we can simply check for length
      // if we have length, there was a match
      // if we have no length, there was no match
      resolve(results.length ? true : false)
    });
  });
};

To call the function… We must wrap in async function if we want to leverage await

(async function(){
  let is_admin = await isAdmin(YOUR_UID_VALUE);
  console.log('is_admin', is_admin);
})();
over 4 years ago · Santiago Trujillo 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