本地数组没有被推送到

时间:2013-09-05 12:37:08

标签: javascript arrays

我有以下代码。尽管成功检索到prices,但数组价格似乎没有被推送到ustock.unitprice数组。

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);
  });
},

这是一个范围问题吗?我不确定为什么prices没有被推到。

非常感谢。

1 个答案:

答案 0 :(得分:1)

如果你知道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();  
         }
       });
     }

  });
},

更新:或根本不需要延迟对象:

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); 
             }
           });
         }

      });
    },