运行 对同一个 table 的两个查询并在同一路由上实现它们

Running two queries on the same table and implement them on the same route

我怎样才能使这个工作?

我想我应该使用 promises,但我对它们知之甚少。我读过它们,但无法创建应有的结构。

我只想 运行 对同一个 table 两个不同的查询,并在同一个 ejs 文件上使用返回值

app.get('/', (req, res) => {

    db.query('SELECT COUNT(*) AS count, FORMAT(SUM(donation_amount),2) AS total FROM donations;', (err, result) => {
        if (err) throw err;
        let count = result[0].count; //since query column is requested as "count". we can use "count" to get back the raw value
        let total = result[0].total;
        res.render('home', { count: count, total: total }); // just the file name is enough. ejs engine looks up the file name in the "views" folder
    });

    db.query('SELECT CONCAT(first_name, ", ", last_name AS latest_donator, donation_amount AS amount FROM donations ORDER BY donation_time LIMIT 1;', (err, result) => {
        if (err) throw err;
        let donatorName = result[0].latest_donator;
        let amount = result[0].amount;
        res.render('home', {first_name: donatorName, amount: amount});
    });
 });

您只有在获得两个查询的结果后才能发送响应 (res.render(...))。因此,您可能希望像这样按顺序执行它们。

app.get('/', (req, res) => {
    db.query('SELECT COUNT(*) AS count, FORMAT(SUM(donation_amount),2) AS total FROM donations;', (err, result) => {
        if (err) throw err;
        let count = result[0].count; //since query column is requested as "count". we can use "count" to get back the raw value
        let total = result[0].total;
        db.query('SELECT CONCAT(first_name, ", ", last_name AS latest_donator, donation_amount AS amount FROM donations ORDER BY donation_time LIMIT 1;', (err, result) => {
            if (err) throw err;
            let donatorName = result[0].latest_donator;
            let amount = result[0].amount;
            res.render('home', { first_name: donatorName, amount: amount, count: count, total: total });
        });
    });
});

但是查询彼此独立,因此您可以 运行 它们并行。