'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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source