Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js NodeJS可以';t在回调中访问变量_Node.js_Mongoose_Locomotivejs - Fatal编程技术网

Node.js NodeJS可以';t在回调中访问变量

Node.js NodeJS可以';t在回调中访问变量,node.js,mongoose,locomotivejs,Node.js,Mongoose,Locomotivejs,我相信这是异步的问题,但我不知道解决方案 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; con

我相信这是异步的问题,但我不知道解决方案

    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
将返回未定义,并且我无法确定如何在页面上显示该表。

问题在于Selling.find是异步的,在执行this.table=table时可能无法完成。试试下面的方法

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();
  });
}
这将保证在获取结果并填充表之前不会使用该表。

如何尝试在函数外部访问“this.table”?对不起,我的意思是变量“table”设置在函数(err,res){}内部,当我尝试将其分配给this.table时,变量“table”为空。