简体   繁体   English

本地数组未推送到

[英]Local array not being pushed to

I have the following code. 我有以下代码。 The array prices does not seem to be pushed to the prices array despite successfully retrieving the ustock.unitprice . 尽管成功检索了ustock.unitprice但阵列价格似乎并未被推到prices阵列中。

getLatestMarketPrices: function(username, callback) {
   var prices = [];
   db.find('portfolio', {user: username}, function(err, stocks) {
     for(var i = 0; i < stocks.length; i++) {
       module.exports.getQuote(stocks[i].stock, function(err, ustock) {
         console.log(ustock.unitprice); // Retrieves 1.092
         prices.push(ustock.unitprice); // Should push to prices array?
       });
     }
   console.log(prices); // Prices is still [] despite earlier push.
   callback(null, prices);
  });
},

Is this a scoping issue? 这是范围问题吗? I'm not really sure why prices is not pushed to. 我不太确定为什么不推高prices

Thanks very much. 非常感谢。

If you know jquery, you could try deferred object 如果您知道jquery,则可以尝试延迟对象

getLatestMarketPrices: function(username, callback) {
   var prices = [];

   var defer = $.Deferred();
  //Attach a handler to be called when the deferred object is resolved
   defer.done(function(){
      console.log(prices); 
      callback(null, prices);
   });

   db.find('portfolio', {user: username}, function(err, stocks) {
     for(var i = 0; i < stocks.length; i++) {
       module.exports.getQuote(stocks[i].stock, function(err, ustock) {
         console.log(ustock.unitprice); // Retrieves 1.092
         prices.push(ustock.unitprice); // Should push to prices array?
         //resolve when we retrieve all
         if (prices.length == stocks.length){
             defer.resolve();  
         }
       });
     }

  });
},

Update: or don't need deferred object at all: 更新:或根本不需要延迟的对象:

getLatestMarketPrices: function(username, callback) {
       var prices = [];

       db.find('portfolio', {user: username}, function(err, stocks) {
         for(var i = 0; i < stocks.length; i++) {
           module.exports.getQuote(stocks[i].stock, function(err, ustock) {
             console.log(ustock.unitprice); // Retrieves 1.092
             prices.push(ustock.unitprice); // Should push to prices array?

             //callback only when we receive all 
             if (prices.length == stocks.length){
                 console.log(prices); 
                 callback(null, prices); 
             }
           });
         }

      });
    },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM