Home > Software design >  Node postgres query returning undefined instead of query result
Node postgres query returning undefined instead of query result

Time:09-01

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.

CodePudding user response:

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

  • Related