1

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; 
2

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Though this answer will solve the problem, in case db.query api has an overload that returns a promise, simply returning db.query(sql) will also solve the problem.
@planet_hunter Thanks for the addon.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.