variables不保留函数外的值

我试图从函数传递数据variables到app.get调用。 但是我的函数中的全局variables'data'没有保留从数据库查询返回的值。 我相信这是一个范围问题。 我在开始时将'data'的值设置为null,以使整个函数中的variables可以被访问。 我没有达到任何一个错误条件。

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')); }); 

有人可以帮我确定为什么“数据”不保留pg.connect函数之外的值吗?

 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) {.....]) 

使用@dystroy提到的callback函数完美工作。

我认为你的问题不是variables不是保留在函数外的值,而是你console.log(数据)在variables设置之前执行。

如果您将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'); }