【问题标题】:pg client.query() does not wait at the awaitpg client.query() 不等待 await
【发布时间】:2021-08-03 18:29:43
【问题描述】:

我不明白为什么 pg 客户端请求前面的 awaitclient.query() 函数内的代码之前运行之后的代码似乎不起作用。

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

我希望上面返回这个:

=> res
=> after res

而是返回:

=> after res
=> res

【问题讨论】:

  • 看起来您正在尝试同时执行回调和异步/等待。

标签: javascript postgresql async-await pg


【解决方案1】:

试试

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;
  })
}

使用承诺:

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);       
    }
  });
}

【讨论】:

    【解决方案2】:

    您似乎正在尝试同时执行回调和异步/等待。

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

    【讨论】:

    • 完美,是的,我还没有完全理解 client.query 和相关回调是如何工作的,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2016-03-08
    • 1970-01-01
    • 2020-07-23
    相关资源
    最近更新 更多