简体   繁体   中英

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, Client} = require('pg')
const connectionString = 'postgressql://user@localhost:5432/database'

const client = new Client({
    connectionString:connectionString
})

client.connect()

database_func()

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

I would expect the above to return this:

=> res
=> after res

Instead it returns:

=> after res
=> res

Try

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

const client = new Client({
    connectionString:connectionString
})

client.connect()

database_func();

function database_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'))

function async database_func() {
  const client = new Client({
    connectionString:connectionString
  });
  client.connect()
  await query_func(client, `SELECT t FROM es ORDER BY t DESC LIMIT 1;`);
  await query_func(client, `SELECT t FROM es ORDER BY t LIMIT 1;`);
  client.end()
}

function query_func(client, query) {
  return new Promise((resolve, reject) => {
    client.query(query, (err,res) => {
      if(err) reject(err);
      resolve(res);       
    }
  });
}

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 = new Client({
    connectionString:connectionString
})

client.connect()

database_func()

async function database_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;
  })

  // OR

  let 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')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM