[英]Accessing a variable that is outside an anonymous function
I have this simple code 我有这个简单的代码
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. '
});
});
},
which i am using to fetch all rows in a mysql table. 我用它来获取mysql表中的所有行。 However inside that function,i want to have another function that counts how many rows there are in the table.My variable var all_rows shows me undefined when i try displaying it.
但是在该函数中,我想要另一个函数来计算表中有多少行。我的变量var all_rows在我尝试显示时显示未定义。 How can i solve this?.
我该怎么解决这个问题?
This is because you are accessing the value of all_rows
before the inner-query has returned. 这是因为您在返回内部查询之前访问
all_rows
的值。
Noder.query
is an asynchronous function, and as such, its execution will be delayed until the query itself is completed. Noder.query
是一个异步函数,因此,它的执行将被延迟,直到查询本身完成。 Meanwhile, your orm
function will continue merrily down and call res.view
while your inner query is still processing. 同时,当您的内部查询仍在处理时,您的
orm
函数将继续快速向下并调用res.view
。
To fix this, you can call res.view
from inside your inner query. 要解决此问题,您可以从内部查询中调用
res.view
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.