[英]Node.js / Javascript - Wait until method is finished
我在寫一個蒸汽交易機器人,但是我的問題是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;
}
}
});
}
如果循環不等到方法完成,則變量i
在該方法中不正確,並且得到錯誤的結果。
編輯 :
現在,當我將@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
}
}
您可以將某些庫用作異步https://github.com/caolan/async 。 與之相關的任何異步周期(每個系列或每個系列)。
async.each(array, function(item, callback){ // do something with a item // call callback when finished callback(); });
以下是完整的工作代碼,希望對您有所幫助:)
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()(); } }
如何使用:
checkItemPricesCashIn(yourOffer/*your offer*/, function(min, max){
//it will be execute just after
console.log('min', min);
console.log('max', max);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.