0

I have a little problem on my app. I would like to get and return the data array outside the anonymous function. I use promise, aim my problem is when I try my service it return a random array lenght with random values.

I do not know the problem, I do not know if I use the 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
        }

and

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

1 Answers1

3

You are overcomplicating things.

In particular, the outer loop isn't necessary, neither is the Deferred.

$http.get() clearly retuns a promise, which can be pushed onto an array and finally aggregated with $q.all().

As far as I can tell, you want the following :

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);
}
Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
  • You need to check that `numberDayPerMonth` array - April, June, September & November have 31 days, Also, for February, [with reference to this answer](https://stackoverflow.com/a/16353241/3478010), you can write `[..., leapYear(year)?29:28, ...]`. – Roamer-1888 Jun 01 '17 at 08:37