NodeJS获取和传递variables

鉴于node.js的asynchronous特性,我在计算variables“通过”(我知道这不是正确的术语,我将解释)时遇到了一些麻烦。

请看下面的内容:

connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if(err) { throw err; } var solution = rows[0].solution; }); res.render('index', { title: solution }); 

正如你可以想象的,我得到一个reference error, solution is not defined 。 这是因为res.render是在从mysql服务器获取解决scheme之前完成的。

一旦解决scheme被定义,我怎样才能使它呈现页面? 我知道这是一个非常小而愚蠢的事情,真的是节点的核心,但请帮助我理解。

connection.query的第二个参数是数据库返回后运行的callback函数。 为什么不把res.render行放在callback中? 这样,渲染function不会被调用,直到你有你的数据准备好。

 connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if(err) throw err; var solution = rows[0].solution; res.render('index', { title: solution }); }); 

当您首次开始使用Node时,callback可能会有点棘手。 您只需要考虑需要发生的步骤以及哪些步骤是asynchronous的。 从那里你只需要确保你的callback让这个过程继续下去。