Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node postgres query returning undefined instead of query result

I am creating a query to my postgres database. The function that makes the query looks like this:

const { pool } = require("./database");

async function getClasses(user) {
  return pool.connect(async function (err, client, done) {
    if (err) {
      console.log(err);
    } else {
      const sqlText = `SELECT * FROM "public"."classes" WHERE "admins" = $1`;
      const values = [user];
      let listOfClasses = await client.query(sqlText, values);
      done();
      console.log(listOfClasses.rows);
      return listOfClasses.rows;
    }
  });
}

module.exports = { getClasses };

The console.log(listOfClasses.rows) has the rows that I am looking for my function to return, but the actual returned value is undefined. I’ve been tinkering with the code for quite a while now and can’t seem to figure it out. Any help here would be much appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to use the promise style api as the callback style call will not return anything (Your function is retuning client.connect(() => { ... }) which return undefined)

const getClasses = (...) => {
  const client = await pool.connect()
  const listOfClasses = await client.query(...);
  return listOfClasses.rows;
}

should do

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading