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;
planet_hunter
  • 3,866
  • 1
  • 26
  • 39
Kunal Shukla
  • 81
  • 1
  • 2
  • 7
  • See [this answer](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jro Mar 18 '19 at 11:40
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ponury-kostek Mar 18 '19 at 11:55

1 Answers1

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.

Zelo101
  • 110
  • 2
  • 6
fedesc
  • 2,554
  • 2
  • 23
  • 39