我正在寫蒸汽機器人來計算已發送物品的價格。我無法正確使用功能。我想從URL獲得價格,然後將其添加到console.log中。異步JavaScript和功能
我不能這樣做,因爲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);
});
}
'whole_price變量不能在回調裏訪問'爲什麼? – Cristy
哇,我修改了代碼,它可以(可能之前,我沒有錯字),但仍然console.log執行循環之前。 – irqize
這是因爲'getPrice'函數是異步的。您必須計算已完成的回調數,並且只在count = offer.itemsToReceive.length時記錄該值。或者您可以使用'async'庫或某個承諾庫並等待所有回調。 https://github.com/caolan/async – Cristy