匿名函数作用域混淆

发布于 2024-11-14 02:29:07 字数 278 浏览 2 评论 0原文

如何将匿名函数内的值分配给全局变量或其范围之外的变量。例如下面的例子。 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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仙女 2024-11-21 02:29:07

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 your result 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 assign rows to it, because the anonymous function is only executed later, when the query is completed.

因为看清所以看轻 2024-11-21 02:29:07

.execute 返回什么?它可能只是处理 .query 返回的项目而不返回数组

What does the .execute returns? It could be just processing the item returned by the .query without returning an array

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文