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);
7
  • 1
    You're doing an asychronous operation with $.getJSON, but you're not waiting for it before you do console.log Commented Oct 30, 2017 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. Commented Oct 30, 2017 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. Commented Oct 30, 2017 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. Commented Oct 30, 2017 at 13:03
  • Hi @Tomalak Thanks a lot, I will look into that. Commented Oct 30, 2017 at 13:05

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.