我正在编写一个 Steam 交易机器人,但我遇到了一个问题,即 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
}
}
最佳答案
下面是完整的工作代码,希望对您有所帮助:)
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);
});
关于javascript - Node.js/Javascript - 等到方法完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34009517/