【问题标题】:Database returned value is undefined in Node JS数据库返回值在 Node JS 中未定义
【发布时间】:2021-03-26 05:19:17
【问题描述】:

我在学习 NodeJS 时遇到了一个问题。我是 javascript 新手,所以任何人都可以向我解释一下。

我正在从 index.js 调用一个函数,该函数将返回从数据库中获取的值。但是我在返回时得到了未定义的对象。

index.js

const cron = require('node-cron');
const app = require('./app');
const port = process.env.PORT || 3000;
require('dotenv').config();

const { getRecentData } = require('./service/getRecentData')

var prev_id = 0;
cron.schedule('*/10 * * * * *', async() => {
    var row = await getRecentData();
    console.log(row);
    var new_id = row["id"];
    if (new_id == prev_id){
        new_id = prev_id;
    }
    else{
        console.log(row["date_time"]);
        prev_id = new_id;
    }
})

app.listen(port, () => {
  console.log(`Listening: http://localhost:${port}`);
});

getRecentData.js

const e = require("express")

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

const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'database',
    password: 'postgres',
    port: 5432,
});

client.connect();

const getRecentData = async () => {
  const query = `
    SELECT *
    FROM test_table order by id desc limit 1
    `;

   const recentData =  await client.query(query, (err, res) => {
        if (err) {
            console.error(err);
            return;
        }
        return res.rows; 
  });

  return recentData;
}


module.exports = {
  getRecentData
}

但是在调用 getRecentData() 函数时,我在 index.js 中得到了未定义的对象。

【问题讨论】:

    标签: node.js express javascript-objects


    【解决方案1】:

    您需要了解await 仅适用于 Promises。如果函数返回一个 Promise,你可以使用await。所有async 函数都返回一个Promise。在您的情况下,client.query 没有返回承诺,它有一个回调,它有自己的执行上下文,因此 return recentData 语句在 client.query 方法完成之前执行。您可以像这样修改getRecentData 方法

    const getRecentData = () => {
        return new Promise((resolve, reject) => {
            const query = `SELECT * FROM test_table order by id desc limit 1`;
            client.query(query, (err, res) => {
                if (err) {
                    console.error(err);
                    reject(err);
                    return;
                }
                resolve(res);
            });
        });
    };
    

    【讨论】:

      【解决方案2】:

      不要使用 recentData 变量

      await client.query(query, (err, res) => {
              if (err) {
                  console.error(err);
                  return;
              }
              if(res){
                   return res.rows; 
              }
        });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-22
        • 1970-01-01
        • 1970-01-01
        • 2020-04-22
        相关资源
        最近更新 更多