node.jspostgresqlasync-awaitnode-pg-pool

Async/Await with node-pg on digitalocean not returning anything


Hi I am trying to fetch data from server/index.js api endpoint data.getData() which is provided from api/data.js which in turn gets it's configuration and connection object from db/index.js. The problem is that the async/await is not returning anything and in the dev console network says pending. I don't receive any errors either. The code is below. Using node-pg with pool.query.

//server/index.js
const express = require("express");
const data = require("./api/data")

const PORT = process.env.PORT || 3001;

const app = express();
app.use(express.json())

app.get('/', async (req, res) => {
    // res.status(200).send('Hello World!');

    await data.getData()
    .then(response => {
      res.status(200).send(console.log(response));
    })
    .catch(error => {
        res.status(500).send(error);
      })
    console.log("server running")
})


app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});


//api/data.js
const db = require('../db/index.js');

const getData = async () => {
    const query = {
        // text: 'SELECT COUNT(*) as count FROM "public"."Subregions-USA";',
        text: 'SELECT Now()',
        // values: ['B007RKDGVQ'],
        // rowMode: 'array',
    };
    
    const dbResults = await db.query(query)
    .then((data) => JSON.stringify(data))
    .catch(error => {
        console.log(error)
      })
    console.log("database response test")

    return dbResults
}

// getData()

module.exports = {getData}

The setup is pretty simple but i can't understand why it is not working. enter image description here

I am trying to connect to postgresql in digital ocean and all the connections and configs are correct. I have used the same setup similar but with electron.js and it works. I am able to retrieve the data easily.

Any help appreciated.


Solution

  • Ok I have found the problem and it has nothing to do with the logic itself but more with the package I installed for PostgreSQL.

    Instead of installing npm i pg I did instead npm i node-pg for some stupid reason.

    After uninstalling and installing the correct package I am able to work with the PostgreSQL response.