I made a function to search a user by email id. I'm calling that function in an async function using await and assigning the returned value to or constant/variable but getting undefined on printing the constant/variable
function search(email) {
sql = `SELECT email FROM users WHERE email = '${email}'`;
db.query(sql, (err, res) => {
if (err) {
console.log(err);
}
else {
return res[0].email;
}
})
}
const auth = async (req, res, next) => {
try {
const token = req.header('Authorization').replace('Bearer', '');
const decoded = jwt.verify(token, 'catisdoguniversaltruth');
const user = await search(decoded._id);
console.log(user);
if (!user) {
throw new Error();
}
next();
}
catch (e) {
res.status(401).send("Not Authenticated, Please login");
}
};
module.exports = auth;
I made a function to search a user by email id. I'm calling that function in an async function using await and assigning the returned value to or constant/variable but getting undefined on printing the constant/variable
function search(email) {
sql = `SELECT email FROM users WHERE email = '${email}'`;
db.query(sql, (err, res) => {
if (err) {
console.log(err);
}
else {
return res[0].email;
}
})
}
const auth = async (req, res, next) => {
try {
const token = req.header('Authorization').replace('Bearer', '');
const decoded = jwt.verify(token, 'catisdoguniversaltruth');
const user = await search(decoded._id);
console.log(user);
if (!user) {
throw new Error();
}
next();
}
catch (e) {
res.status(401).send("Not Authenticated, Please login");
}
};
module.exports = auth;
Share
Improve this question
edited Mar 18, 2019 at 11:51
planet_hunter
3,9861 gold badge29 silver badges42 bronze badges
asked Mar 18, 2019 at 11:37
Kunal ShuklaKunal Shukla
811 gold badge2 silver badges7 bronze badges
2
- See this answer – jro Commented Mar 18, 2019 at 11:40
- 1 Possible duplicate of How do I return the response from an asynchronous call? – ponury-kostek Commented Mar 18, 2019 at 11:55
1 Answer
Reset to default 6You need search()
to be a promise and not a function.
await
waits for a promise to resolve.
Try this:
function search(email) {
return new Promise((resolve, reject) => {
sql = `SELECT email FROM users WHERE email = '${email}'`;
db.query(sql, (err, res) => {
if (err) {
reject(err);
}
else {
resolve(res[0].email);
}
})
})
}
This will be resolved as promise and auth()
will wait.
You could also build search()
as async/await
promise. Doesn't really matter as long as you return a promise resolve.