简体   繁体   中英

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 .

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.

Thanks very much.

If you know jquery, you could try deferred object

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

      });
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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