NodeJS Can't Access Variable Inside Callback

前端 未结 1 1963
孤街浪徒
孤街浪徒 2020-12-21 11:04

I believe this is a problem with it being async, but I do not know the solution.

    PagesController.buy = function() {

  var table=\"\";
  Selling.find({},         


        
相关标签:
1条回答
  • 2020-12-21 11:20

    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.

    0 讨论(0)
提交回复
热议问题