NodeJS无法访问回调内部的变量 [英] NodeJS Can't Access Variable Inside Callback
本文介绍了NodeJS无法访问回调内部的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为这是异步的问题,但我不知道解决方案.
I believe this is a problem with it being async, but I do not know the solution.
PagesController.buy = function() {
var table="";
Selling.find({}, function(err, res) {
for (var i in res) {
console.log(res[i].addr);
table = table + "res[i].addr";
}
});
this.table = table;
console.log(table);
this.render();
}
我的问题是,如果我尝试在函数外部访问this.table=table
,则会返回undefined,并且我无法弄清楚如何在页面上显示表格.
My issue is that this.table=table
is returning undefined if I try access it outside of the function, and I cannot figure out how to display the table on the page.
推荐答案
问题是Selling.find是异步的,并且可能在执行this.table = table时尚未完成.尝试以下类似的方法.
The problem is the Selling.find is asynchronous and likely isn't complete by the time the this.table = table is executed. Try something like the following.
PagesController.buy = function() {
var that = this;
Selling.find({}, function(err, res) {
var table = '';
for (var i in res) {
console.log(res[i].addr);
table = table + res[i].addr;
}
that.table = table;
console.log(table);
that.render();
});
}
这将确保在获取结果并填充表之后才使用表.
That will guarantee that table isn't used until after the results have been fetched and table has been populated.
这篇关于NodeJS无法访问回调内部的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文