如何从两个异步函数中获取变量的值
How to get the value of variable out of two async functions
我想写一个代码,其中有几个货币的数组。我想要得到数组中这些货币组合的汇率。例如,如果我有一个这样的数组:
['美元','澳元','英镑'],然后我想获得转换的价值,如:
美元-> 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>
相关文章:
- 使用jQuery来foreach iframe-src,并通过函数获取ID和操作
- Javascript函数获取元素内容
- 从Javascript函数获取字符串
- Jasmine测试工厂函数调用本地函数和另一个函数-获取错误:应该是间谍,但得到了function
- 从 JavaScript 函数获取 NaN 尝试多次获取相同的数据
- 从 JS 函数获取 PHP 中的值
- 如何用一个函数获取所有javascript变量
- Javascript-函数获取数组元素参数未定义/为null
- 从回调函数获取xhr状态
- 有没有一种方法可以让watch函数获取被监视文件的名称
- 从JQuery到Javascript函数获取表单对象
- 使用react.js从api函数获取json数据
- 从javascript中的递归函数获取undefined
- 使用sails.js中的beforeConnect函数获取客户端套接字
- 如何通过类名和过滤函数获取属性值
- 从php函数获取值到javascript
- 从外部函数获取参数名称
- 从方法js中的函数获取对象属性
- 使用Jquery.load()函数获取变量和页面片段
- 使用onclick函数获取点击的元素jquery