2016-01-17 117 views
0

我正在寫蒸汽機器人來計算已發送物品的價格。我無法正確使用功能。我想從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+'&currency=USD'; 
      request(url, function(error, res, body){ 
       body = JSON.parse(body); 
       price = body.median_price; 
      }); 
     } 

     callback(price); 
    }); 

} 
+1

'whole_price變量不能在回調裏訪問'爲什麼? – Cristy

+0

哇,我修改了代碼,它可以(可能之前,我沒有錯字),但仍然console.log執行循環之前。 – irqize

+1

這是因爲'getPrice'函數是異步的。您必須計算已完成的回調數,並且只在count = offer.itemsToReceive.length時記錄該值。或者您可以使用'async'庫或某個承諾庫並等待所有回調。 https://github.com/caolan/async – Cristy

回答

3

做這樣的事情的最佳方法是...

var whole_price = 0; 
var requestsMade = 0; 
for(var i=0 ; i<offer.itemsToReceive.length; i++){ 
    requestsMade++; 
    getPrice(offer.itemsToReceive[i].market_hash_name, function(price){ 
     whole_price += price; 
     requestsMade++; 

     if(requestsMade == offer.itemsToReceive.length-1) 
     { 
      console.log(YOUR MESSAGE); 
     } 
    }); 
} 

這基本上確保你不記錄我直到所有請求都已完成並作出響應。這是因爲即使所有呼叫都是按特定順序進行的,它們也可以按不同的順序完成。

+0

謝謝你們,你救了我的底部:D – irqize

2

你應該考慮使用async library,讓你的生活更輕鬆。不要重新發明輪子!

var whole_price = 0; 

async.each(offer.itemsToReceive, function (item, next) { 

    getPrice(item.market_hash_name, (price) => { 
     whole_price += price; 
     next(); 
    }); 

}, function() { 

    console.log(whole_price); 
});