我正在尝试使用async / await从postresql数据库获取数据。我面临的问题是fetchMembers会加载数据,但不会返回该数据,而只会返回一个空白对象。
//server.js
const members = require('./memberDB')
app.get('/' , (req, res) => {
res.json(members)
console.log('Members: ',JSON.stringify(members))
})
//MemberDB.js
const fetchMembers = async function() {
const { Client, Pool } = require('pg')
const pool = new Pool({
user: 'user',
host: 'localhost',
database: 'whatevs',
password: '',
port: 5432,
})
const loadData = await pool.query('SELECT * FROM members;')
const data = await loadData.rows
console.log('data -> ', data)//I get this data correctly
return data // but I don't get the return value even if I remove 'await' from the 'loadData.rows'
}
module.exports.members = fetchMembers()
答案 0 :(得分:1)
make fetchMembers返回一个promise,并在请求处理程序中等待它。
const fetchMembers = async function() {
const { Client, Pool } = require('pg')
const pool = new Pool({
user: 'user',
host: 'localhost',
database: 'whatevs',
password: '',
port: 5432,
})
return pool.query('SELECT * FROM members;')
}
module.exports.members = fetchMembers;
在路线中:
app.get('/' , async (req, res) => {
const loadData = await fetchMembers();
const data = loadData.rows;
res.json(data);
})
问题在于您调用fetchMembers并等待其中的诺言,但这不会阻塞代码。继续执行req处理程序,并且尚未解析成员。因此,您有两种解决方案要么在fetchMembers和请求处理程序中等待,要么返回承诺并仅在请求处理程序中等待。就像保罗所说的那样,最好是导出函数本身。
答案 1 :(得分:1)
# file = "C:/Users/PycharmProjects/MindNotez/"
file_path = "C:/Users/PycharmProjects/MindNotez/"
df_content = {"title": [], "author": [], "year": [], "others": [], "note": []}
# for file in os.listdir(file):
for file in os.listdir(file_path):
if file.endswith("Note.csv"):
# file_content = file + "Note.csv"
file_content = file_path + "Note.csv"
return file_content
else:
df = pd.DataFrame(data=df_content)
# df.to_csv(file + "Note.csv", sep=",", index=False)
df.to_csv(file_path + "Note.csv", sep=",", index=False)
file_content = file + "Note.csv"
return file_content
导出调用counting: for i = 1:5
println(i)
end counting
的结果,该结果是MemberDB.js
函数,因此将始终返回fetchMembers()
。
async
答案 2 :(得分:1)
您在需要文件时调用该函数,但不等待它。这有两个效果。首先,您的members变量将没有数据,其次,由于您需要调用它,因此由于缓存的原因,您在第一次需要该文件时只会获得数据库中的任何成员。正确的方法是像这样导出函数:
module.exports = fetchMembers; // note no parentheses
然后正确呼叫您的路线:
const fetchMembers = require(“./dbMembers”);
app.get(‘/‘, async (req, res) => {
const members = await fetchMembers();
res.send(members); // obviously add erro catching and stuff
});
答案 3 :(得分:0)
将函数包装在try catch语句中,这样就不会出现静默错误,例如:
const fetchMembers = async () => {
try
{
const { Pool } = require('pg')
const pool = new Pool({
user: 'user',
host: 'localhost',
database: 'whatevs',
password: '',
port: 5432,
})
return await pool.query('SELECT * FROM members;')
}
catch(reason){
console.log(reason)
}
}
console.log(fetchMembers())