Skip to content Skip to sidebar Skip to footer

Pg Client.query() Does Not Wait At The Await

I am don't understand why the await in front of a pg client request does not seem to work as the code after it runs before the code inside the client.query() function. const {Pool,

Solution 1:

It looks like you're trying to do callbacks and async/await at the same time.

const {Pool, Client} = require('pg')
const connectionString = 'postgressql://user@localhost:5432/database'const client = newClient({
    connectionString:connectionString
})

client.connect()

database_func()

asyncfunctiondatabase_func() {
  // You should be doing callbacks OR async/await whenever you call a query,// You're doing both at the same time

  client.query(`SELECT t FROM es ORDER BY t DESC LIMIT 1;`, (err,res) => {
    console.log('res')
    return;
  })

  // ORlet res;
  try {
    res = await client.query(`SELECT t FROM es ORDER BY t DESC LIMIT 1;`);
  } catch (err) {
    console.error(err);
  }

  console.log(res);
  
  client.end();
  
  console.log('after res')
}

Solution 2:

Try

const {Pool, Client} = require('pg')
const connectionString = 'postgressql://user@localhost:5432/database'const client = newClient({
    connectionString:connectionString
})

client.connect()

database_func();

functiondatabase_func() {
  client.query(`SELECT t FROM es ORDER BY t DESC LIMIT 1;`, (err,res) => {
    console.log('res')
    client.end()
    console.log('after res')
    return;
  })
}

Using promise:

const {Pool, Client} = require('pg')
const connectionString = 'postgressql://user@localhost:5432/database'database_func().then(() =>console.log('done'))

functionasyncdatabase_func() {
  const client = newClient({
    connectionString:connectionString
  });
  client.connect()
  awaitquery_func(client, `SELECT t FROM es ORDER BY t DESC LIMIT 1;`);
  awaitquery_func(client, `SELECT t FROM es ORDER BY t LIMIT 1;`);
  client.end()
}

functionquery_func(client, query) {
  returnnewPromise((resolve, reject) => {
    client.query(query, (err,res) => {
      if(err) reject(err);
      resolve(res);       
    }
  });
}

Post a Comment for "Pg Client.query() Does Not Wait At The Await"