0
getValue = ( url, callback) ->
  $.getJSON url, (json) ->
    value = json.last
    callback value


$(window).load ->

  btsx_btc = getValue "http://data.bter.com/api/1/ticker/btsx_btc", (data) ->
    $('#v_btsx_btc').html data

  btc_usd = getValue "http://data.bter.com/api/1/ticker/btc_usd", (data) ->
    $('#v_btc_usd').html data

  $('#v_btsx_usd').html btsx_btc*btc_usd

I'm pretty new to JavaScript and Coffeescript. I can succesfully retrieve 2 values (btsx_btc & btsc_USD). I want to multiply those 2 variables and show it in the middle one. But its not working, the console is not showing any errors. I presume that the 2 variables are empty somehow. I hope you guys can help

http://i.imgur.com/gTDaDpD.png

This is the output javascript

(function() {
  var getValue;

  getValue = function(url, callback) {
    return $.getJSON(url, function(json) {
      var value;
      value = json.last;
      return callback(value);
    });
  };

  $(window).load(function() {
    var btc_usd, btsx_btc;
    btsx_btc = getValue("http://data.bter.com/api/1/ticker/btsx_btc", function(data) {
      return $('#v_btsx_btc').html(data);
    });
    btc_usd = getValue("http://data.bter.com/api/1/ticker/btc_usd", function(data) {
      return $('#v_btc_usd').html(data);
    });
    return $('#v_btsx_usd').html(btsx_btc * btc_usd);
  });

}).call(this);
Sharpless512
  • 3,062
  • 5
  • 35
  • 60

1 Answers1

1

btc_usd and btsx_btc are promises, not numbers! You cannot simply multiply them - and you can't make the asynchronous getJSON return a number. Instead, use jQuery.when to wait for both values to arrive:

getValue = (url) ->
  $.getJSON url
  .then (json) ->
    json.last

$(window).load ->
  btsx_btc = getValue "http://data.bter.com/api/1/ticker/btsx_btc"
  btsx_btc.done (data) ->
    $('#v_btsx_btc').html data

  btc_usd = getValue "http://data.bter.com/api/1/ticker/btc_usd"
  btc_usd.done (data) ->
    $('#v_btc_usd').html data

  $.when btsx_btc, btc_usd
  .done (data1, data2) ->
    $('#v_btsx_usd').html data1*data2
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I just had to remove the [ ] from data1 and data2 since its 1 value and not a array because I already did .last on the json in the getValue function. Then it worked perfect! Thanks! – Sharpless512 Aug 26 '14 at 10:39
  • Right, I missed that neither `getJSON` nor the custom `then` mapping return multiple arguments. – Bergi Aug 26 '14 at 11:35