Why do I assign a value to an object and return 0?

0
class Coin{
  constructor(){
    this.price = 0.00;
    this.total = 0.00;
  }
}

function main(){
  const coin= new Coin();
  price(coin);
  ver(coin);
}

function price(coin){
  var cont = 0.00;
  var tot = 0.00;
  $.ajax({
    url: 'https://api.bitfinex.com/v1/pubticker/btcusd',
    dataType: 'json', 
    success: function(data_response){  
      tot += parseFloat(data_response.last_price);
      cont++;
      coin.price = (tot/cont);
      transform(coin);
    },
    error: function(data){
      console.log*d
    }
  });
}

  function transform(coin){
    $.ajax({
        url: 'https://blockchain.info/q/addressbalance/1ACAgPuFFidYzPMXbiKptSrwT74Dg8hq2v',
        dataType: 'json', 
        success: function(data_response){  
            coin.total += parseFloat(data_response * Math.pow(10,-8));
        },
        error: function(data){
            console.log(data);
        }
    });   
  }

  function ver(coin){
      console.log(coin.total);
  }

  main();

I would like to know why it returns 0 if the total changes it previously.

    
asked by Oscar Ordoñez 09.05.2018 в 20:27
source

2 answers

2

If you want to change the value of coin , you should declare it as a variable, not as a constant;

Like this:

var coin = new Coin();

This way you can alter its value during the execution of the program.

When being called asynchronous, you should call the method see in the success of your last ajax call:

 function transform(coin){
    $.ajax({
        url: 'https://blockchain.info/q/addressbalance/1ACAgPuFFidYzPMXbiKptSrwT74Dg8hq2v',
        dataType: 'json', 
        success: function(data_response){  
            coin.total += parseFloat(data_response * Math.pow(10,-8));
            ver(coin);
        },
        error: function(data){
            console.log(data);
        }
    });   
  }

your main would look like this:

function main(){
  const coin= new Coin();
  price(coin);
}
    
answered by 09.05.2018 в 20:31
1

Your problem is here:

function main(){
  const coin= new Coin();
  price(coin);
  ver(coin);
}

The price () function generates two Ajax calls which are asynchronous. When you call the function see (), the two calls have not yet returned. If you want to see the correct result, move the call to see () within the success () of the last Ajax call.

    
answered by 09.05.2018 в 20:32