我正在寫一個蒸汽交易機器人,但我有問題,for循環不會等到for循環內的方法完成。所以代碼不能像它應該那樣工作。Node.js/Javascript - 等待方法完成
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
}
}
感謝此代碼。但現在,當我將這段代碼放入函數中返回總值和最小值時,該函數在方法可以改變它們之前返回值。見上面編輯... – jeanggi90
看我的更新,希望這個幫助 – Cleiton