Node.js / Javascript – 等到方法完成

我正在写一个蒸汽交易机器人,但我有一个问题,for循环不会等到for循环内部的方法完成。 所以代码不能正常工作。

for (i = 0; i < offer.itemsToReceive.length; i++) { console.log(offer.itemsToReceive[i].market_hash_name); community.getMarketItem(appid.CSGO, offer.itemsToReceive[i].market_hash_name, function(err, items) { if (err) { Winston.error("Error getting Marketprice"); } else { var cacheItemPrice = items.lowestPrice; totalValue += items.lowestPrice; Winston.info("Item " + offer.itemsToReceive[i].market_hash_name + " is " + items.lowestPrice + " Cents worth"); if (items.lowestPrice <= minValue) { minValue = items.lowestPrice; } } }); } 

如果循环没有等到方法结束,variablesi在方法中是不正确的,我得到了一个错误的结果。

编辑
现在,当我把@Cleiton的代码放到我想要返回两个值的函数中时,函数会在方法有时间更改之前返回值。

 function checkItemPricesCashIn(offer) { Winston.info("Getting itemprices from trade #" + offer.id); var totalValue = 0; var minValue = 50; var executionList = []; function getMarketItem(item) { var market_hash_name = item.market_hash_name; return function() { community.getMarketItem(appid.CSGO, market_hash_name, function(err, items) { if (err) { Winston.error("Error getting Marketprice"); } else { var cacheItemPrice = items.lowestPrice; totalValue += items.lowestPrice; Winston.info("Item " + market_hash_name + " is " + items.lowestPrice + " Cents worth"); if (items.lowestPrice <= minValue) { minValue = items.lowestPrice; } } (executionList.shift() || function() {})(); }); } } offer.itemsToReceive.forEach(function(item) { executionList.push(getMarketItem(item)); }); if (executionList.length) { executionList.shift()(); } console.log(totalValue); console.log(minValue); return { totalValue: totalValue, minValue: minValue } } 

下面是一个完整的工作代码,我希望这有助于:)

 function checkItemPricesCashIn(offer, cb) { Winston.info("Getting itemprices from trade #" + offer.id); var totalValue = 0; var minValue = 50; var executionList = []; function getMarketItem(item) { var market_hash_name = item.market_hash_name; return function() { community.getMarketItem(appid.CSGO, market_hash_name, function(err, items) { if (err) { Winston.error("Error getting Marketprice"); } else { var cacheItemPrice = items.lowestPrice; totalValue += items.lowestPrice; Winston.info("Item " + market_hash_name + " is " + items.lowestPrice + " Cents worth"); if (items.lowestPrice <= minValue) { minValue = items.lowestPrice; } } (executionList.shift() || cb)(minValue,totalValue); }); } } offer.itemsToReceive.forEach(function(item) { executionList.push(getMarketItem(item)); }); if (executionList.length) { executionList.shift()(); } } 

你可以使用一些库async https://github.com/caolan/async 。 并与它每个系列或只是每个asynchronous周期。

 async.each(array, function(item, callback){ // do something with a item // call callback when finished callback(); });