异步 JavaScript 和函数

Asynchronous JavaScript and functions

我正在编写计算已发送物品价格的 Steam 机器人。我无法正确使用功能。我想从 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+'&currency=USD';
            request(url, function(error, res, body){
                body = JSON.parse(body);
                price = body.median_price;
            });
        }

        callback(price);
    });

}

做这样的事情的最好方法是...

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);
        }
    }); 
}

这基本上是为了确保您在所有请求都已发出并得到响应之前不会记录消息。这是因为即使所有调用都是按特定顺序进行的,它们也可能会以不同的顺序完成。

您应该考虑使用 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);
});