我想编写一个代码,其中包含几种货币。我想获取数组中这些货币组合的汇率。
即如果我有这样的数组:
['USD','AUD','GBP'],那么我想获取转化价值,例如:
USD-> AUD,USD-> GBP,AUD-> USD,AUD-> GBP,GBP-> USD,GBP-> AUD。要获得实时汇率,我在这里使用了货币api:http://currency-api.appspot.com
因为我有某种重复,所以我使用了for循环来为json的ajax请求创建url。创建网址后,我将它们保存到ur数组中,并将转换名称保存到curr数组中,以便可以使用相同的索引来引用ur数组和curr数组。
现在成为棘手的部分
遍历URL并获取我使用$ .each进行的每种货币转换的实时货币值,以及在$ .each内部的$ .ajax。
现在,在获得了I的值之后,我将其存储到了一个数组中-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)我认为这是一个异步问题,我也尝试使用控制台返回的回调函数,没有回调函数错误
Fiddle
最佳答案
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
关于javascript - 如何从两个异步函数中获取变量的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33163988/