簡體   English   中英

pg client.query() 不等待 await

[英]pg client.query() does not wait at the await

我不明白為什么pg客戶端請求前面的awaitclient.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')
}

我希望上面能返回這個:

=> res
=> after res

相反,它返回:

=> after res
=> res

嘗試

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

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

看起來您正在嘗試同時進行回調和異步/等待。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM