0

I have this strange scope issue with the while loop below. If I place console.log inside both the function and while loop I get the result I'm looking for, but for the code below I get nothing at all. It seems that the .push method is not pushing the values into the arrays CCY and dts. Any ideas how I can fix this issue?

  var CCY=[]; 
  var dts=[]; 
  var start = new Date(x);
  var end = new Date(y);
  while(start < end){

    var newDate = start.setDate(start.getDate() + 1);
    start = new Date(newDate);
    var d = (start.toISOString().split('T')[0]);
    var JSONItems=[];

        $.getJSON("http://api.fixer.io/"+d, function(data){
       JSONItems = data;

        CCY.push([JSONItems.rates.USD]);
        dts.push([JSONItems.date])   


        });
    } 

    console.log("Date= "+dts);   
    console.log("Rate= "+CCY);
Micke
  • 29
  • 5
  • 1
    You're doing an asychronous operation with `$.getJSON`, but you're not waiting for it before you do console.log – TKoL Oct 30 '17 at 12:54
  • In other words, the browser does these things in order: 1) sends request for getJSON, 2) ` console.log("Date= "+dts); `, 3) receives result for getJSON, 4) pushes onto dts array. – TKoL Oct 30 '17 at 12:55
  • Yes, exactly. You need to register a callback for the moment when your last request is done. You should look into `$.when()` for how to do that with jQuery. Besides the official documentation there are many working examples on this site. – Tomalak Oct 30 '17 at 12:59
  • Hi @TKoL Thanks for the quick reply. I can see that this is actually a duplicate question, so I will look at the answer to that and hope I can figure out how to fix it. – Micke Oct 30 '17 at 13:03
  • Hi @Tomalak Thanks a lot, I will look into that. – Micke Oct 30 '17 at 13:05
  • The duplicate looks at the problem in a more generic manner, but there are countless down-to-earth examples, too. For example https://stackoverflow.com/questions/14352139/multiple-ajax-calls-from-array-and-handle-callback-when-completed – Tomalak Oct 30 '17 at 13:24
  • I don't seem to get my head around this. I tried to change `$.getJSON("http://api.fixer.io/"+d, function(data){` to `$.getJSON("http://api.fixer.io/"+d).done(functiondata){` to fix the issue with not waiting for the results. But it still doesn't work. I have also tried a bunch of other stuff with no result. Can someone show me how it's done using my code? I'm really stuck here. – Micke Oct 31 '17 at 11:52

0 Answers0