【问题标题】:How can I use more than one query in Node-postgres?如何在 Node-postgres 中使用多个查询?
【发布时间】:2020-09-22 07:00:40
【问题描述】:

所以我不确定 node-pg 是如何工作的,但我一直试图通过环顾四周、尝试一些事情并阅读文档一段时间来使其工作。我想要实现的是能够在不同的时间发送多个查询,但是如果我敢于编写第二个查询,那么在我发送第一个查询后它总是会抛出错误。这个问题已经在网上被问过多次,但我认为没有任何帮助答案。如果有必要,我可以使用池化(这也有问题)。

现在有效:(它在 heroku 上,所以我必须使用 process.env.DATABASE_URL)

const { Client } = require('pg');

const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
  }
});
client.connect()

client

.query('SELECT * FROM test WHERE....')
.then(results => {
console.log(results);
}

.catch(err => {
console.log(err.stack)
 })

我要做什么:

const { Client } = require('pg');

const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
  }
});
client.connect()

client

.query('SELECT * FROM test1 WHERE....')
.then(results => {
console.log("FIRST RESULTS: "results);
}

.catch(err => {
console.log(err.stack)
 })

.query('SELECT * FROM test2 WHERE....')
.then(results => {
console.log("SECOND RESULTS: "results);
}

.catch(err => {
console.log(err.stack)
 })

【问题讨论】:

  • 我尝试了很多东西,所以我得到了多个不同的错误。我可能做得不对,但我在网上找不到任何示例,其中有多个查询,这就是我来这里的原因。在使用池时,当我使用像这个例子这样的特定客户端时:node-postgres.com/features/pooling 在第二个查询中,错误是 ''client.query(...).then(...).query is not a function'',而没有客户端的情况类似:“TypeError: pool.query(...).then(...).catch(...).query is not a function”

标签: node.js postgresql node-postgres


【解决方案1】:

当您 .query 时,会返回一个 Promise,并且 Promise 没有 .query 方法 - 您可以对 Promise 执行的所有操作就是在其上调用 .then.catch(或 .finally,有时)。

如果您想在旧查询完成后进行新查询,请在 .then 内调用 client.query

client
  .query('SELECT * FROM test1 WHERE....')
  .then(results => {
      console.log("FIRST RESULTS: " + results);
    })
    .then(() => client.query('SELECT * FROM test2 WHERE....'))
    .then(results => {
      console.log("SECOND RESULTS: " + results);
    })
    .catch(err => {
      // better to handle errors at the end, probably
      console.log(err.stack)
    })

如果第二个查询依赖于第一个查询的结果,请考虑改用async 函数,以使代码更扁平且更具可读性。

如果第二个查询依赖于第一个查询的结果,请考虑改用Promise.all,这样两个查询可以同时进行,而不必等待第一个查询完成首先。

【讨论】:

  • 非常感谢。最后,这行得通。这回答了我的问题,所以我接受了它,但我不确定如果我稍后需要在不同的代码块中进行更多查询,我应该怎么做。我可以再次调用包含相同进程的函数吗? “Client.query(..).then(..)”,因为当我尝试这样做时,我又遇到了另一个错误。它在连续的 .THEN 中运行良好,但我不知道在其他情况下该怎么做。如果您愿意提供更多帮助,我将不胜感激。谢谢。
  • 任何时候您有更多查询要运行,将它们返回到.thens 中,以便下一个.then 可以处理它们的解析值。如果您想一次运行两个查询,请执行 return Promise.all([client.query(...), client.query(..)]).then(([result1, result2]) => { /* do stuff with result1 and result2 */
  • 谢谢你,我想我在你的帮助下想通了。希望最后一个问题,我什么时候应该使用 client.end()?如果我在使用后理解正确,那么我将无法再次发送任何查询,甚至无法以某种方式重新打开它,对吗?
  • 我想你会在完成后调用它,就像在 finally 之后一样。 .catch(...).finally(() => { client.end(); });
猜你喜欢
  • 2016-03-18
  • 2016-06-08
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 2015-08-30
  • 1970-01-01
  • 2012-01-05
  • 2020-04-03
相关资源
最近更新 更多