这是我的代码:如何当使用pg如果我从函数返回我的查询结果,它返回未定义,但如果我控制台登录它,它打印?
const queryFirstNames = function (qString) {
let firstNameMatches;
client.query('SELECT * FROM famous_people WHERE first_name = $1', [qString], (err, result) => {
if (err) {
return console.error('error running query', err);
}
firstNameMatches = result.rows;
return firstNameMatches;
client.end();
});
};
console.log(queryFirstNames(qString));
});
This code return undefined and doesn't end the connection with the database
但如果我CONSOLE.LOG的功能,而不是返回,然后只需调用该函数没有控制台日志里面firstNameMatches,I get the result I want, and the database connection closes properly.
我想要什么要做的是返回这个查询的结果并在另一个函数中使用它,所以我不希望它控制台记录结果,但是当我尝试返回结果时,它给了我未定义的,并且不关闭数据库连接。
非常感谢这 - 你说的话很有道理。然而,看起来firstNameMatches变量在客户端.end()之前只有一个值**所以当我运行你的代码时,它返回并且console.logs未定义,但是如果我在查询中使用console.log,firstNameMatches ,它输出一个值。 就好像firstNameMatches不存在于查询的范围之外,即使我在父函数中定义了它 –
所以我多了一些代码,好像当我重置firstNameMatches **的值时**查询,它不会保留,所以当我在查询之外返回firstNameMatches时,它将返回它原来的值,而不是我在查询中设置的值。 –