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
我对 JavaScript 和 Coffeescript 还很陌生。我可以成功检索 2 个值(btsx_btc 和 btsc_USD)。我想将这两个变量相乘并将其显示在中间的变量中。但它不起作用,控制台没有显示任何错误。我认为这两个变量不知何故为空。希望大家能够帮忙
这是输出的 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);
最佳答案
btc_usd
和 btsx_btc
是 promise ,而不是数字!你不能简单地将它们相乘 - 而你can't make the asynchronous getJSON
return a number 。相反,使用 jQuery.when
等待两个值到达:
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
关于javascript - 乘以从API检索的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25503032/