如何在javascript中从异步函数传递参数?

时间:2015-12-03 06:20:10

标签: javascript json asynchronous

我试图从两个异步函数向函数传递两个值,我不知道如何继续。这是代码:

    var btcPriceInUSD;
var priceExchangeMXN;
var btcLink = "https://blockchain.info/ticker";
var exchangeRateLink = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%29&env=store://datatables.org/alltableswithkeys&format=json";

//Get btc price in USD
$.getJSON(btcLink, function(btcData) 
    {   
        btcPriceInUSD = btcData.USD.last;
        //document.write(btcPriceInUSD);
    });     


//Get current USD/MXN exchange rate
$.getJSON(exchangeRateLink, function(exchangeData) 
    {   
        priceExchangeMXN = exchangeData.query.results.rate.Rate;
        //document.write(priceExchangeMXN);
    });     


//Convert btc price to MXN
function convertToMXN(btc,toMXN){
    var result = parseFloat(btc) * parseFloat(toMXN);
    document.write(result);
}


convertToMXN(btcPriceInUSD,priceExchangeMXN)

我知道问题是我在非同步之外调用这个函数所以它没有收到数字而且它给了我一个NAN(不是数字)但是我不知道我怎么会正确传递在不同函数中检索的那两个参数,是否可以将btcPriceInUSD和priceExchangeMXN合并为一个并从那里调用它?

提前致谢!

2 个答案:

答案 0 :(得分:3)

尝试使用$.when().then(),将完整函数的返回值替换为声明异步函数范围之外的变量;还添加了错误处理程序

$.when($.getJSON(btcLink, function(btcData) {   
        return btcData.USD.last
       })     
, $.getJSON(exchangeRateLink, function(exchangeData) {   
        return exchangeData.query.results.rate.Rate
    }))
.then(convertToMXN, function err() {console.log(arguments)})

答案 1 :(得分:1)

尝试这个(简单地链接ajax调用,最后在两个值都可用时调用方法)

var btcPriceInUSD;
var priceExchangeMXN;
var btcLink = "https://blockchain.info/ticker";
var exchangeRateLink = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%29&env=store://datatables.org/alltableswithkeys&format=json";

//Get btc price in USD
$.getJSON(btcLink, function(btcData) 
    {   
        btcPriceInUSD = btcData.USD.last;
        //document.write(btcPriceInUSD);

      //Get current USD/MXN exchange rate
      $.getJSON(exchangeRateLink, function(exchangeData) 
        {   
           priceExchangeMXN = exchangeData.query.results.rate.Rate;
            //document.write(priceExchangeMXN);
           convertToMXN(btcPriceInUSD,priceExchangeMXN);
        });  

    });     

//Convert btc price to MXN
function convertToMXN(btc,toMXN){
    var result = parseFloat(btc) * parseFloat(toMXN);
    document.write(result);
}