繁体   English   中英

javascript node.js 从 sql 查询中设置一个变量来计算表中的行数

[英]javascript node.js set a variable from sql query to count rows in a table

我的 node.js javascript 程序中有一个(postgres sql)表。 我只是想确定其中有多少行,并将该值分配给可以在代码进行时使用的变量(n)。

编辑 编辑 编辑 - 根据要求,我现在包含了更多令人惊讶的代码,并且我尝试使用提供的第一个答案。

db_connnection.query(display_query).then(result => {
        io.to(roomId).emit('room-display-update', result.rows);
        // console.log(result.rows); 
      
       const queryFunction = async (db_connnection) => {
            var n = await db_connnection.query("SELECT COUNT(*) as total FROM waypoint", function(err,Result) {
                   return parseInt(Result.total);
            });
            console.log("There are", n, "inside queryfunction"); // this is never called?
            return n
        };
        
        var nn = queryFunction(db_connnection);
        console.log("There are", nn, "outside queryfunction"); // returns the follwoing
        // There are Promise {<rejected> TypeError: Cannot read property 'query' of undefined at queryFunction (/app/server.js:49:42) ...

我已经尝试了很多方法,目前如上所述,但我明显缺乏编码知识或技能。 一切要么是无效类型错误,要么返回“未定义”或“承诺”。

如何让变量n包含数字2 (在这种情况下)?

所以现在有问题的代码看起来像这样,每个都显示当前的 console.log 错误:

        var count_query = "SELECT COUNT(*) as total FROM waypoint" 
        async function Countit(count_query) {
            const ioResult = await db_connnection.query(count_query).then(async (result) => { 
            console.log("There are", result.total, "inside function") // There are undefined inside function
            return parseInt(result.total);
            })
        console.log("There are", ioResult.total, "inside ioResult") // There are undefined inside ioResult
        };
        var nn = Countit(count_query);
        console.log("There are", nn, "outside function"); //  There are Promise { <pending> } outside function

数据库调用是异步的,您试图在数据库返回值之前记录该值。 将您的调用转换为 async/await 或 promise/resolve 语句。

const queryFunction = async (db_connection) => {
      var n = await db_connnection.query("SELECT COUNT(*) as total FROM maintable", function(err,Result) {
                return parseInt(Result.total);
        });
        console.log("Print", n);
        return n
};

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM