ExpressJS MySql Pool Connection Query Return

I am just starting in ExpressJS. So here console.log works, so if I make a call, I do see it in terminal result dataset printed. But, it doesn’t return it as response. I do console.log and return but still get no data in response..

index.js

...
app.get("/", async (req, res) => {
  let data = await queries();
  res.json(data);
});
...

Also tried

...
app.get("/", (req, res) => {
  res.json(queries());
});
...

queries.js

function main(sql) {
  return pool.getConnection((err, connection) => {
    if (err) throw err;
    return connection.query(sql, (errt, rows) => {
      connection.release(); // return the connection to pool
      if (errt) throw err;
      console.log(rows);
      return rows;
    });
  });
}
function queries() {
  let Q = "SELECT * FROM `items`";
  return main(Q);
}

Answer

I believe the problem is in the function main() if you do see the result in the terminal. Your functions in the index.js file seems okay. The issue is probably due to the promise not being sent back from the main() function in queries.js file. You need to do 2 things –

  1. Wrap the functionality of the main() in a Promise and return that promise. The callback function of the Promise object takes resolve(use this to return result) and reject(use this to return error).

  2. As the main() will return a promise, you queries() function needs to be async, therefore needs to await the return from the main().

I have attached an Image to show how I implemented this for a DNS-lookup function. You will find some similarities.

Example function for returning promise

// Notice the resolve and reject are functions
function main(sql) {

    return new Promise((resolve, reject) => {
       pool.getConnection((err, connection) => {
        if (err) throw err;
         connection.query(sql, (errt, rows) => {
          connection.release(); // return the connection to pool
          if (errt) throw err;
          console.log(rows);
          resolve(rows);
        });
      });
    });
}


async function queries() {
  let Q = "SELECT * FROM `items`";
  let result = await main(Q);
  return result;
}

I believe this should work. Give it a try and good luck!