gpt4 book ai didi

javascript - 获取数据 promise angularJS

转载 作者:行者123 更新时间:2023-11-28 17:56:49 25 4
gpt4 key购买 nike

我的应用程序有一点问题。我想获取并返回匿名函数外部的数据数组。我使用 promise ,目标是我的问题是当我尝试我的服务时,它返回一个带有随机值的随机数组长度。

我不知道问题所在,我不知道我是否使用了promise。

getCurrentExchangeTo : function(year, month, country){

var def = $q.defer();

var numberDayPerMonth = [
31,
9,
31,
30,
31,
30,
31,
30,
31,
30,
31,
30,
];

var vm = this;
this.country = country;

this.getCurrentExchangeFor = [];
var hello = "gello"

for(var i = 0; i < numberDayPerMonth.length; i++){
if((i + 1) === month){
for(let j = 1; j < numberDayPerMonth[i]; j++){
$http.get('http://api.fixer.io/2000-02-0' + j + '?symbols=USD').then(function (success) {
let countryDay = vm.country
vm.getCurrentExchangeFor[j] = success.data.rates[countryDay];
def.resolve(getCurrentExchangeFor)
});
}
}
}
return def.promise
}

    getCurrentExchangeService.getCurrentExchangeTo(2015, 2, 'USD').then(function (data) {
console.log(data)
});

最佳答案

你把事情搞得太复杂了。

特别是,外循环不是必需的,Deferred 也不是必需的。

$http.get() 明确地重新调整了一个 Promise,它可以被推送到一个数组中,并最终与 $q.all() 聚合。

据我所知,您想要以下内容:

getCurrentExchangeTo: function(year, month, country) {
var numberDayPerMonth = [ 31, 29, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30 ];
var promises = [];
for(let i=1; i<=numberDayPerMonth[month-1]; i++) {
promises.push($http.get('http://api.fixer.io/2000-02-0' + i + '?symbols=USD').then(function(response) {
return response.data.rates[country];
}));
}
return $q.all(promises);
}

关于javascript - 获取数据 promise angularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44293699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com