0

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)

ruleboy21
  • 5,510
  • 4
  • 17
  • 34
Leon
  • 103
  • 7
  • You can ref to the solution in the link this[How do I create a MySQL connection pool while working with NodeJS and Express?](https://stackoverflow.com/questions/37102364/how-do-i-create-a-mysql-connection-pool-while-working-with-nodejs-and-express) – lost you Apr 18 '22 at 08:43
  • is that post not just how to store the connection pool in variable isn't it? – Leon Apr 18 '22 at 08:57
  • You need call getConnection to check your server is exists or not. – lost you Apr 18 '22 at 09:06
  • the db is working. when i console.log() the res before the return, i get the right output. The problem is, that i cant store it in h. – Leon Apr 18 '22 at 09:12
  • you can console.log(res) before return, or you can use localstorage to save them – lost you Apr 18 '22 at 09:18
  • yes, i can console.log(res) before returning. I also get the expected result. I just can't use the output then. and it has to have a solution to save the output in a variable without using localstorage – Leon Apr 18 '22 at 09:25

1 Answers1

4

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...
})()
Ben
  • 1,331
  • 2
  • 8
  • 15