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

124
Visualizações
cannot access result set outside the function using mysql in nodejs

I cannot access the result set outside its scope.

function getAllProducts() {
   connection.connect((err) => {
      if (err) throw err
      connection.query(
         'SELECT * FROM `men`', (err, result) => {
            if (err) throw err
            return result
            });
         })
   })
}

I have tried reassigning it to a previously created variable by adding this let res = null, replacing return statement with res = result and returning res at the end of the function and instead.

I have also tried reassigning it by iterating through it by creating an empty array called res and replacing return statement with this :

result.forEach(element => {
    res.push(element)
})

I can console log it by replacing return statement with console.log(result) and it would work normally and print the result set.

I'm starting to figure out that it has something to do with the last line executing before callback finishes executing so it returns nothing. any help is appreciated to guide me to right direction on figuring this out.

about 4 years ago · Juan Pablo Isaza
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