Reputation: 77
Whenever i try to fetch the return value from a function it returns undefined.
Tried callbacks, Tried async
let express = require('express');
let fs = require('fs');
let router = express();
let mysql = require('mysql');
const session = require('express-session');
router.use(session({
secret: 'something random.exe',
resave: false,
saveUninitialized: true,
cookie: {
expires: new Date(Date.now() + 7600000),
maxAge: new Date(Date.now() + 7600000),
}
}));
async function logins (username, password) {
mysql.createQuery("SELECT * FROM Users WHERE username = ?", [username], (err, rows) => {
return "test";
})
}
module.exports = {
login: async (request, response, username, password) => {
logins("username", "password", (getResponse) => {
return console.log(getResponse);
})
}
};
The console always returns undefined.
Upvotes: 0
Views: 639
Reputation: 2111
It seems to be you are not aware of async/await
keyword. This type of issue occurs when you try to call any function without the keyword await
.
WRONG FORMAT
const userUtils = {};
userUtils.login = async () => {
try {
// Your business logic
} catch (err) {
console.log(err);
throw err;
}
};
userUtils.test = async () => {
try {
const result = userUtils.login();
console.log(result); // It will undefined
} catch (err) {
console.log(err);
throw err;
}
};
userUtils.test();
In the above code, you will get undefined
as result variable.
CORRECTION
const result = await userUtils.login();
Don't forget to write a keyword await
while calling any promises.
Note: You can only use async/await
when you need to handle any promises. It can't work directly on callbacks
WRONG FORMAT [await while callbacks]
userUtils.test = async () => {
try {
const result = await userUtils.login(args, (err, data) => {
if (err) {
console.log(err);
throw err;
}
return data;
});
console.log(result); // It will undefined
} catch (err) {
console.log(err);
throw err;
}
};
I hope it helps. Happy Coding :)
Upvotes: 0
Reputation: 943754
When you call logins
you pass it three arguments:
Look at the definition of logins
:
async function logins (username, password) {
It only does anything with the first two arguments.
Your callback function never gets used.
Rewrite logins
to call it.
Also note that you've labeled it as async
, but you aren't await
ing any promises … so that is probably a mistake.
Upvotes: 4