【发布时间】: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