Javascript 变量未在函数外保留值
我正在尝试将数据变量从函数传递到app.get调用。 但是函数中的全局变量“data”没有保留从数据库查询返回的值。我认为这是一个范围问题。我在开始时将“data”的值设置为null,以使变量在整个函数中都可以访问。我没有遇到任何错误条件Javascript 变量未在函数外保留值,javascript,node.js,Javascript,Node.js,我正在尝试将数据变量从函数传递到app.get调用。 但是函数中的全局变量“data”没有保留从数据库查询返回的值。我认为这是一个范围问题。我在开始时将“data”的值设置为null,以使变量在整个函数中都可以访问。我没有遇到任何错误条件 function getCommands(query) { var data = null; try { pg.connect(cString, function(err, client, done) { // Cat
function getCommands(query) {
var data = null;
try {
pg.connect(cString, function(err, client, done) {
// Catch any connection errors, and display them to the screen
if(err) {
return console.error('could not connect to postgres', err);
}
client.query(query, function(q_err, result) {
// Release the client back to the pool
done();
if(q_err) {
return console.error('error running query', q_err);
}
// Data object with an empty array to hold the row information
data = {"data":[]};
for (var row in result.rows)
{
//console.log(result.rows[row]);
data.data.push(result.rows[row]);
}
//Here, data, has the correct return values.
console.log(data);
});
});
}
catch( e )
{
console.log(e);
}
//Here, data, is null.
console.log(data);
return data;
}
app.get('/clients/', function(req, res) {
res.send(getCommands('SELECT clientid, clientname FROM hourglass.clients ORDER BY clientid ASC'));
});
有人能帮我确定为什么“data”没有保留pg.connect函数之外的值吗?我认为您的问题不是变量没有保留函数之外的值,而是您在设置变量之前正在执行console.log(data) 如果将
console.log('step X')
放入代码中,如以下示例所示,您将看到代码的执行顺序
function getCommands(query) {
var data = null;
console.log('STEP 1');
pg.connect(cString, function(err, client, done) {
console.log('STEP 3');
});
console.log('STEP 2');
}
使用@dystroy提到的回调函数效果很好。它的可能重复项不会“保留”该值,因为在调用回调之前记录了该值。您不能从异步计算该值的函数返回值。我建议您研究解决该问题的承诺。我写了一篇关于如何将它们用于postgres访问的文章:感谢您指出代码中的异步问题。由于这段代码的简单性,我选择了执行回调函数,而不是实现承诺。此代码现在按计划工作。由于我是网站的“新手”,我现在还不能发布我的新代码作为答案。但我会在第一次发帖的8小时过后再发帖。再次感谢你的帮助!不客气。很高兴看到您理解了。是的,我不是在试图修复他的代码,而是通过console.log(“步骤X”)行向他展示步骤的执行情况。
function getCommands(query, callback) {
try {
pg.connect(cString, function(err, client, done) {
// Catch any connection errors, and display them to the screen
if(err) {
return console.error('could not connect to postgres', err);
}
client.query(query, function(q_err, result) {
// Release the client back to the pool
done();
if(q_err) {
return console.error('error running query', q_err);
}
// Data object with an empty array to hold the row information
var data = {"data":[]};
for (var row in result.rows)
{
data.data.push(result.rows[row]);
}
callback(data); //After data is set, the value is passed back
});
});
}
catch( e )
{
console.log(e);
}
}
app.get('/clients', function(req, res) {.....])