i am trying to get data from MySQL database using node.js and i need to use it on other modules so i need to send query result it seem so easy but i get stuck :
i get data using this calss and funcation:
class user{
user(){}
static async getUser(email: string) {
let Finalresult = await DataBase.query("SELECT * FROM childcare.user where email =?", [email], function (err, result, fields) {
if (err) return err;
else
return result;
});
return Finalresult;
} }
module.exports = user;
i want to use data in that function and i expect to get the result of query
const userModule = require("../../modules/user");
static async login(req: Request, res: Response) {
const { email, password } = req.body;
const user = await userModule.getUser(email);
console.log('user is ', user);)}
But i get
user is *<ref 1> Query
2
Answers
You can’t use then/catch and async/await together. You need to remove the callback part.
In your calling module:
The issue you’re encountering is related to the fact that you are using a callback function to handle the query result in your
getUser
method. Theawait
keyword doesn’t work as expected with functions that use callbacks.To make your code work as expected, you can either use a Promise-based approach with
util.promisify
to convert the callback-based function into a Promise, or you can use a library likemysql2
which has built-in support for Promises. Here’s how you can do it usingmysql2
:First, you need to install
mysql2
if you haven’t already:Then, you can modify your
getUser
method as follows:Make sure to replace
'your_host'
,'your_user'
,'your_password'
, and'your_database'
with your actual MySQL database connection details.Now, your
getUser
method will return the query result as expected, and you can use it in yourlogin
function:With this setup, your code should work correctly, and you will get the actual query result in the
user
variable.