如何从两个异步函数中获取变量的值

How to get the value of variable out of two async functions

本文关键字:函数 获取 变量 异步 两个      更新时间:2023-09-26

我想写一个代码,其中有几个货币的数组。我想要得到数组中这些货币组合的汇率。例如,如果我有一个这样的数组:
['美元','澳元','英镑'],然后我想获得转换的价值,如:
美元-> AUD,美元->英镑,澳元->美元,澳元->英镑,英镑->美元,英镑->澳大利亚。为了获得实时货币汇率,我使用了货币api: http://currency-api.appspot.com因为我有一种重复,我已经使用for循环来创建json的ajax请求的url。在我创建url之后,我已经将它们保存到ur数组中,并且在curr数组中也保存了转换名称,这样我就可以使用相同的索引来引用ur数组和curr数组。

棘手的部分来了

循环遍历url并获得我使用$进行的每个货币转换的实时货币值。每个,和$。每个都有$.ajax。现在,在我得到的值之后,我已经将它存储到一个数组——an_array。

最后在$。end和$.ajax),当我试图打印an_array的值时,它是空的。

var currencies = ['AUD','USD','INR','GBP'];
var ur = [];
var curr = [];
var curr_val = [];
var an_array = [];
for (var i = 0; i < currencies.length; i++) {
  for (var j = 0; j < currencies.length; j++) {
    if (i != j) {
      cont = 'https://currency-api.appspot.com/api/' + currencies[i] + '/' + currencies[j] + '.jsonp';
      tex = currencies[i] + ' ' + currencies[j]
      curr.push(tex);
      ur.push(cont);
    }
  }
}
$.each(ur, function (index, value) {
  $.ajax({
    url: value,
    dataType: "jsonp",
    data: {amount: '1.00'},
    success: function (response) {
      result = response.rate;
      an_array.push(result);
    }
  });
});
console.log(an_array)
/*This is returning [], but should return array with values. 
 I can't move this line from here, to inside, 
 I have logged it here because I want to check whether its working, 
 I want to perform calculations for the values coming out from here.*/

注意:1)我已经尝试过ajax的。done()方法
2)我认为这是一个异步问题,我也尝试了回调函数,其中控制台返回,没有回调函数错误

小提琴

这绝对是一个异步问题。您可以使用jQuery deferred来轻松地完成此操作。

$.when.apply($, $.map(ur, function(value, index) {
  return $.ajax(...) /* without "success" */
}).then(function(results) {
  ...
  console.log(...);
});

在后台,when计算您的完成情况,当所有请求都完成时,执行then处理程序。

不使用延迟的低技术解决方案是全部手动完成:

var totalAjaxCalls = ur.length;
$.each(ur, ...
  ...
    success: function(response) {
      result = response.rate;
      an_array.push(result);
      if (!(--totalAjaxCalls)) {
        console.log("All results available");
        console.log(results);
      }
    }
    ...

var ur = [];
var curr = [];
var curr_val = [];
var an_array = [];
var calculationWithResult = function( myArrayForCalculation ){
 
  // Make your calculation here
  console.log( 'Every call has been made : ' , myArrayForCalculation );
  
}
for(var i=0;i<currencies.length;i++){
    for(var j=0;j<currencies.length;j++){
        if(i!=j){
            cont = 'https://currency-api.appspot.com/api/'+currencies[i]+'/'+currencies[j]+'.jsonp';
            tex = currencies[i]+' '+currencies[j]
            curr.push(tex);
            ur.push(cont);
            }
        }
    }
var numberOfURL = ur.length;
console.log('we wait for '  + numberOfURL + ' ajax call ');
$.each(ur,function(index,value){
     $.ajax({
             url: value,
             dataType: "jsonp",
             data: {amount: '1.00'},
             success: function(response) {
               
               numberOfURL = numberOfURL-1
               console.log('rest of ajaxCall : ' + numberOfURL); 
               
               result = response.rate;
               an_array.push(result);
                      
               if(numberOfURL===0) calculationWithResult( result ); // make your stuff
               
               console.log(an_array);//<-------HERE
             }//                               |
              //                               |
              //                               |
 });//                                         |
});//                                          |
//                                             |     
//console.log(an_array) |----------------- MOVE THIS

为什么不这样写呢:

var currencies = { "USD": {},"AUD": {},"GBP": {} };
var currencyValuesLength = Object.keys( currencies ).length * ( Object.keys( currencies ).length - 1 );
// when all done
function whenAllDone() {
    $.each( currencies, function( currency_from, values ) {
        $.each( currencies[ currency_from ], function( currency_to, value ) {
            $( document.body ).append( $( "<div>" + currency_from + " -> " + currency_to + " = " + value + "</div>" ) );
        } );
    } );
}
// get values
function getValues() {
    $.each( currencies, function( currency_from, values ) {
        $.each( currencies, function( currency_to, value ) {
            if ( currency_from != currency_to ) {
                $.ajax( {
            	    url: "https://currency-api.appspot.com/api/" + currency_from + "/" + currency_to + ".jsonp",
                    dataType: "jsonp",
                    data: {
                        amount: "1.00"
                    },
                    method: "POST",
                    success: function( response ) {
                        currencies[ currency_from ][ currency_to ] = response.rate;
                        var currentLength = 0;
                        $.each( currencies, function( currency, values_temp ) {
                             currentLength += Object.keys( values_temp ).length;
                        } );
                        if ( currentLength == currencyValuesLength ) {
                            whenAllDone();
                        }
                    }
                } );
            }
        } );
    } );
}
// onload
$( function() {
    getValues();
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>