简体   繁体   English

(node/express) 从数据库查询中收集多条数据并发送到 index.ejs?

[英](node/express) Collecting multiple pieces of data from database queries and sending to index.ejs?

I'm obtaining multiple pieces of info from a postgres database and using them to render a web page via express in node.我从 postgres 数据库中获取多条信息,并使用它们通过 node.js 中的 express 呈现网页。

I can make a single query of the "measurements" database and pass it in no problem eg:我可以对“测量”数据库进行一次查询,然后毫无问题地传递它,例如:

    pool.query("SELECT * from measurements", (err, result) => {
  if(err) {
    throw err;
  } else {
    var set1= JSON.stringify(result);
    app.get("/", (req, res) => { res.render("index", { set1: set1}); });
  }
});

My issue is making multiple queries and rendering them all together.我的问题是进行多个查询并将它们一起呈现。 At first I tried to store the query results in separate variables outside of a function and passing all of them like so:起初,我尝试将查询结果存储在函数外部的单独变量中,并像这样传递所有变量:

var set1= pool.query("SELECT * from measurements");
var set2= pool.query("DIFFERENT QUERY* from measurements");

app.get("/", (req, res) => { res.render("index", { set1: set1, set2: set2 }); });

but that didn't work because of promises/synchronous method (I think) because it just tells me it's awaiting a promise (or something like that, I can't quite remember).但这并没有因为承诺/同步方法(我认为)而起作用,因为它只是告诉我它正在等待承诺(或类似的东西,我不太记得了)。 I tried to use some await stuff as a fix but nothing worked.我尝试使用一些等待的东西作为修复,但没有任何效果。 (or I wasn't implementing correctly) (或者我没有正确实施)

So what's the best way to do this?那么最好的方法是什么? I thought about either:我想过:

  1. build a function that makes all the necessary queries, declares the variables, and then renders the page at the end using all of them (I think this is where await/async works?)构建一个函数来进行所有必要的查询,声明变量,然后使用所有这些变量在最后呈现页面(我认为这是 await/async 工作的地方?)

  2. somehow combining all the query results into a single object and just sending that single object with all the data, then sorting/classifying/displaying it on the client side.以某种方式将所有查询结果组合到一个对象中,然后将所有数据与该单个对象一起发送,然后在客户端对其进行排序/分类/显示。 (or just sending the whole database to the client, but that seems like a bad idea) (或者只是将整个数据库发送给客户端,但这似乎是一个坏主意)

but I'm not exactly sure the best way to do either of these.但我不确定执行其中任何一项的最佳方法。 Any help would be appreciated, am new to JS任何帮助将不胜感激,我是 JS 新手

Well doing it with async / await is pretty straight forward:使用async / await做得好非常简单:

app.get("/", async (req, res) => {
  var set1 = await getMeasurments("SELECT * FORM BLABLA");
  var set2 = await getMeasurments("SELECT * FORM BLABLA");
  res.render("index", { set1, set2 });
});

function getMeasurments(query) {
  return new Promise((res, rej) => {
    pool.query(query, (err, result) => {
      if (err) {
        rej(err);
      } else {
        res(result);
      }
    });
  });
}

Just make a new function and promisfy it只需创建一个新功能并承诺它

const query = async(query) => {
  const client = await pool.connect()
  const result = await client.query(query)
  client.release()
  return result; 
})

const requests = [
    query("SELECT * from measurements"), 
    query("DIFFERENT QUERY* from measurements")
]
Promise.All(requests).then(results => {
    return results.reduce((acc, curr) => {
        return Object.assign(acc, curr)
    }, {})
}).then(data => {
   res.render("index", data)
})

Taking your initial code, you can, first (1), promisify the pool.query and then (2) call it with await inside an async function;使用您的初始代码,您可以首先(1)promisify pool.query ,然后(2)在async函数中使用await调用它; and (3) use the composed function in you get route和(3)在你的路线中使用组合函数

const poolquery = util.promisify(pool.query);   // (1)

async function renderindex(req,res) {   // (2)
  try {
    let set1 = await poolquery ("SELECT * FROM SET1 ...");
    let set2 = await poolquery ("SELECT * FROM SET2 ..."); 
    res.render("index", { set1, set2 });
  } catch (err) {
    res.status(500).send(err);
  }
}

app.get("/", renderindex);   // (3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用 Express.js 获取 Index.ejs - Cannot Get Index.ejs Using Express.js 将数据从 data.json 文件解析为 index.ejs (expressJS) - Parse data into index.ejs from data.json file (expressJS) 如何将数据从一个 app.js 文件发送到 Routes 中的 index.ejs 文件 - how do I send data from one app.js file to index.ejs file in Routes 如何访问index.ejs的javascript部分中的本地数据(视图)? - How to access locals data in javascript part of index.ejs (view)? 来自 sql 数据库的数据不会在 EJS 页面上呈现,除非它处于循环中(使用 node、express、ejs、mysql) - Data from sql database is not rendering on EJS page unless it is in a loop (using node, express, ejs, mysql) 在index.ejs中显示multer(音乐)文件 - Displaying multer (music) files in index.ejs 将对象从服务器发送到客户端(node / express / ejs) - Sending an object from the server to the client (node/express/ejs) index.ejs中的Angular Controller错误 - Angular Controller error in index.ejs 从 index.ejs 文件提交查询以从 mongodb 集合返回特定文档 - submit query from index.ejs file to return a specific document from a mongodb collection 如何通过app.js将另一个.js文件中所需的功能传递到index.ejs视图中 - How to pass function required from another .js file into an index.ejs view via app.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM