How to make a function containing a select query return results in the overall function return - Node MySQL (npm package)

37 Views Asked by At

I am contacting you today because I am stuck on an error that is preventing me from moving forward. My problem is the following, I have code entirely done in OOP, the problem lies in an asynchronous method of my class. The problem function is called getDatabaseValues ​​and contains a select query with MySQL. The problem is the following, when I try to return the results of the selection query in the general return of the getDatabaseValues ​​function the result is undefined whereas if I do a console.log of the results in getDatabaseValues ​​no problem. Here is my code of my getDatabaseValues method:

// Asynchronous method to retrieve information from the database
async getDatabaseValues() {
  return new Promise(async (resolve, reject) => {
    try {
      // Create a DatabaseManager instance
      const databaseManager = new DatabaseManager();
      // Create a database connection
      await databaseManager.connect();

      // Retrieve the contents of the live table
      const request = "SELECT * FROM live";
      databaseManager.connection.query(request, (error, results) => {
       // Close the connection after making the request
       databaseManager.close();

       // If an error occurred, reject it
       if (error) {
         reject(error);
        } else {
         // Resolve the promise with the results retrieved from the database
         resolve(results[0]);
        }
      });
    } catch (error) {
      // If an error occurred during connection, reject it
      reject(error);
    }
  });
}

Is it possible to leave the code in this form? What should I change? Am I using the Node MySQL query method?

I tried returning the results with a Promise hoping that resolve would make the result usable everywhere in the code but that's not the case! I want getDatabaseValues ​​to return the results from the select query and have the results accessible anywhere in the code in this form:

const databaseValues = await this.getDatabaseValues();
// If the result contains a title field, be able to use it in this way
const title = databaseValues.title; 

Knowing the power of the Stackoverflow community I decided to ask my first question. Hoping to receive some help. Thanking you in advance, have a nice day!

1

There are 1 best solutions below

2
JSmart523 On

Async functions already return promises.

So you are returning a promise of a promise, here.

Try replacing async with function?