0

I have created an AuthController.js file for handling MYSQL DB Query operation. For example, I'm taking one example i.e I created one fucntion in AuthController.js file for checking if particular email is exist or not in database and return a data value from it, here is my code:-

export const IsEmailExistRepo = async (email) => {
  const selectEmailQuery = "SELECT email FROM users WHERE email=?";
  const QueryResult = await db_connect().query(
    selectEmailQuery,
    [email],
    (err, data) => {
      if (err) throw err;
      return data;
    }
  );
  return QueryResult;
};

db_connect() is just a connection object of MYSQL connection instance. So, I want if an email is found then the function IsEmailExistRepo() will return data(which is an email) but in current senario it's not happening, instead of returning data it returns a MYSQL connection object functions and events list.

I also use a callback for this and it's completely working fine but I don't want to do with callback because it creates a problem in AuthServices.js file where I put all my business logic for this for handling custom error for an API.

export const IsEmailExistRepo = (email, callback) => {
  const selectEmailQuery = "SELECT email FROM users WHERE email=?";
  const QueryResult = db_connect().query(
    selectEmailQuery,
    [email],
    (err, data) => {
      if (err) callback(err, null);
      callback(null, data);
    }
  );
  return QueryResult;
};

So I want to return a data result using async/await, I even tried using local variable and then return from the function after storing it but its also not working(due to await may be). Hwo can I do that?

Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38
  • Does this answer your question? [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) – Sadeed_pv Jul 06 '23 at 06:27

1 Answers1

0

To use async/await, you need to wrap the query method in a Promise. Here's how you can do it

export const IsEmailExistRepo = (email) => {
    return new Promise((resolve, reject) => {
        const selectEmailQuery = 'SELECT email FROM users WHERE email=?'
        db_connect().query(selectEmailQuery, [email], (err, data) => {
            if(err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
}
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85