我正在编写计算已发送物品价格的蒸汽机器人。我无法正确使用函数。我想从 URL 中获取价格,然后将其添加到 console.log 中。
我做不到,因为 console.log 在循环之前执行。
我真的是 Javascript 的新手,我无法修复它:(
var whole_price = 0;
for(var i=0 ; i<offer.itemsToReceive.length; i++){
getPrice(offer.itemsToReceive[i].market_hash_name, function(price){
whole_price += price;
});
}
console.log('Accepted offer from ' + offer.partner + ' with ' + offer.itemsToReceive.length + ' items valued as '+whole_price+'$.' );
获取 URL 价格的函数:
function getPrice(name, callback){
name = name.replace(/\ +/g, '%20');
var url = 'http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name='+name;
var price = 0;
request(url ,function(error, res, body){
var useCSGOBACKPACK = false;
if(!error && res.statusCode == 200){
body = JSON.parse(body);
if(body.success == true){
price = body.median_price.substr(1);
}else{
useCSGOBACKPACK = true;
}
}else{
useCSGOBACKPACK = true;
}
if(useCSGOBACKPACK==true){
url = 'http://csgobackpack.net/api/GetItemPrice/?id='+name+'¤cy=USD';
request(url, function(error, res, body){
body = JSON.parse(body);
price = body.median_price;
});
}
callback(price);
});
}