匿名函数作用域混淆
如何将匿名函数内的值分配给全局变量或其范围之外的变量。例如下面的例子。 console.log(rows)
返回正确的数据,而 console.log(result)
返回未定义
var result;
this.query(sql).execute(function(error, rows) {
console.log( rows )
result = rows;
});
console.log( result );
How can I assign values inside an anonymous function to global variables, or variables outside its scope. For instance, the example below. console.log(rows)
returns the right data, while console.log(result)
returns undefined
var result;
this.query(sql).execute(function(error, rows) {
console.log( rows )
result = rows;
});
console.log( result );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Node.js 是事件驱动的,这意味着大多数功能都是异步的。
execute
函数不返回任何值,因为“返回”值位于声明为第一个参数的匿名函数中,该函数仅在执行查询并且已获取值时才会被调用。由数据库返回。因此,您的result
变量不包含任何值,因为还没有任何内容可返回。** 编辑 **
即使在编辑之后,记录变量
结果
的行也会在分配行 到它,因为匿名函数仅在查询完成后才执行。
Node.js is event driven, meaning that most of the functions are asynchronous. The
execute
function does not return any value, because the "returned" value is in the anonymous function declared as your first argument, which function will be called only when the query has been executed and a value has been returned by the database. So yourresult
variable does not contain any value, because there's nothing to return yet.** EDIT **
Even after your edit, the line where you log the variable
result
is executed before you assignrows
to it, because the anonymous function is only executed later, when the query is completed..execute
返回什么?它可能只是处理.query
返回的项目而不返回数组What does the
.execute
returns? It could be just processing the item returned by the.query
without returning an array