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

465
Visualizações
Store MySql query output in a variable (Node js)

I want to make an sql query and want to store the output in a variable. I can't find any solution to make that work, can anyone help me please?

const { createPool } = require("mysql")

const pool = createPool({
    host:"localhost",
    user:"root",
    password:"",
    database:"ticketsystem",
    connectionLimit:10
})

const h = pool.query("select * from tblusers;", (err, res) => {
    return res
})

console.log(h)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your problem is related to the asynchronous nature of the JavaScript execution: the code located in the pool.query's callback function runs after the assignation of the h variable and after the console.log.

You have 2 options:

  1. You can place your entire follow up code inside the callback function:
pool.query("select * from tblusers;", (err, res) => {
  const h = res
  // do whatever comes next here...
})
  1. Promisify the result of the callback function and await its resolution before moving on
const h = await new Promise((resolve) => {
  pool.query("select * from tblusers;", (err, res) => {
    resolve(res)
  })
})

console.log(h)
// do whatever comes next here...

Note that if you are not using one of the latest versions of node (supporting top level await), you will have to place everything in an IIFE function:

(async () => {
  const pool = createPool({
    host:"localhost",
    user:"root",
    password:"",
    database:"ticketsystem",
    connectionLimit:10
  })

  const h = await new Promise((resolve) => {
    pool.query("select * from tblusers;", (err, res) => {
      resolve(res)
    })
  })

  console.log(h)
  // do whatever comes next 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