2017-05-31 6 views
0

私のアプリには少し問題があります。私は取得し、無名関数の外でデータ配列を返したいと思います。私は約束を使用し、私の問題はランダムな値でランダムな配列の長さを返すサービスをしようとすることです。データの取得をお待ちしておりますangularJS

私はこの問題を知らないが、私は約束を使うかどうか分からない。

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) 
    }); 
+0

JavaScriptを非同期..ですuはループが続くとAPIを呼び出し続けるAPIを呼び出すとき:

は、私の知る限り、次欲しいです。それぞれの呼び出しは別の時間に戻ります。したがって、あなたは乱数を得ます... – ziaulain

+0

この権利..しかし、あなたは私の問題の結果についての考えを持っていますか? – simonmnt

+0

return文は、ループ内のresolve文の後に来る必要があります。 –

答えて

3

あなたは物事が複雑になり過ぎています。

特に、外部ループは必要ではなく、どちらも遅延型ではありません。

$http.get()は明らかに約束を返し、配列にプッシュして最後に$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); 
} 
+0

大変ありがとうございます。 – simonmnt

+0

あなたは 'numberDayPerMonth'配列 - 4月、6月、9月、11月は31日、 2月の[この回答を参照して](https://stackoverflow.com/a/16353241/3478010)に '[...、leapYear(year)?29:28、...]'と書くことができます。 –

関連する問題