Search code examples
javascriptnode.jssteamsteambot

Asynchronous JavaScript and functions


I'm writing steam bot that calculates price of sent items. I can't use functions properly. I want to get price from URL then to add it up and console.log.

I can't do it, because console.log executes before the loop.

I'm really new to Javascript and I can't fix it :(

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+'$.' );

Function getting the price for 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);
    });

}

Solution

  • Best way to do something like this is...

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

    this is basically making sure you don't log the message until all requests have been made and responded to. This is because even though all the calls are made in a specific order they may complete in a different order.