【问题标题】:Node/Express render multiple postgres queries on same html fileNode/Express 在同一个 html 文件上呈现多个 postgres 查询
【发布时间】:2020-09-25 17:50:29
【问题描述】:

我有一个从我的数据库返回结果的查询,但我不知道如何让它给我多个查询的结果。

router.get("/", function(req, res) {
  pg.query("SELECT * from tic", (err, done) => {
    if (err) {
      console.log(err);
    }
    res.render("index", { tic: done.rows });
  });
});

我一直在尝试这样做,但由于他的渲染语句在查询中,所以无法让它工作,当我将它移出那里时,我可以得到渲染以查看结果

router.get("/", function(req, res) {
  pg.query("SELECT * from tic", (err, tic) => {
    if (err) {
      console.log(err);
    }
  pg.query("SELECT * from tac", (err, tac) => {
    if (err) {
      console.log(err);
    }
  });
  res.render("index", { tic: tic.rows }, { tac: tac.rows});
});

【问题讨论】:

  • 将两个查询包装在 Promise 中,并在完成后合并它们的结果

标签: node.js express


【解决方案1】:

您只需要在第二个查询执行后进行渲染。为此,您必须在第二个查询的回调中呈现。

router.get("/", function (req, res) {
    pg.query("SELECT * from tic", (err, tic) => {
        if (err) {
            console.log(err);
        }
        pg.query("SELECT * from tac", (err, tac) => {
            if (err) {
                console.log(err);
            }
            res.render("index", { tic: tic.rows }, { tac: tac.rows });
        });
    });
});

【讨论】:

    猜你喜欢
    • 2019-02-14
    • 2013-06-10
    • 2021-03-05
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 2017-11-12
    相关资源
    最近更新 更多