2013-09-05 4 views
1

У меня есть следующий код. Цены на массивы, похоже, не попадают в массив 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 не нажал.

Большое спасибо.

+0

ли db.find вызов асинхронной? – DaveParsons

+0

Да. Он имеет обратный вызов ('функция (err, запасы)'). Вы думаете, что мне нужно переадресовать внешний массив на каждой итерации? Благодарю. –

+0

Это потому, что 'console.log' вызывается до завершения' getQuote() '. – Andy

ответ

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

    }); 
}, 

Update: или не нужно отложенный объект вообще:

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

     }); 
    }, 
+0

Спасибо, Хан. Я попробую это и дам вам знать. –

+0

@Sam Saint-Pettersen: Я сделал некоторые настройки –

+0

Хорошо. Спасибо. –

Смежные вопросы