我有这个简单的代码
orm: function (req, res) {
// Send a JSON response
Noder.query('SELECT * FROM crud ', function(err, results) {
var all_rows = Noder.query('SELECT count(*) from crud ', function(err, the_rows) {
return the_rows;
});
res.view('noder/orm', {
layout: 'layout',
allr:all_rows,
post:results,
title: 'This is the hi page title. '
});
});
},
我正在使用它来获取 mysql 表中的所有行。但是在该函数内部,我想要另一个函数来计算表中有多少行。我的变量 var all_rows 在我尝试显示它时显示未定义。我该如何解决这个问题?
最佳答案
这是因为您在内部查询返回之前访问了 all_rows
的值。
Node.query
是一个异步函数,因此,它的执行将延迟到查询本身完成。同时,您的 orm
函数将继续愉快地向下调用 res.view
,而您的内部查询仍在处理中。
要解决此问题,您可以从内部查询中调用 res.view
。
关于javascript - 访问匿名函数外部的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34464811/