Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!