0

Why is the arr data only available inside the json function? The first console.log returns data the second is an empty array? Do I need to end the first call or somehow copy to a dynamic array?

 var inputURL;
    var start = "2016-09-01";  
    var end = "2016-09-06"; 
    var arr = [];
    var stock = ["AZN.L", "GOOGL", "AAPL"];

    var arrayLength = stock.length;
    for (var i = 0; i < arrayLength; i++) {
        itern(stock[i]);
    };


    function itern (stock) {

     inputURL = "http://query.yahooapis.com/v1/public/yql" +
        "?q=select%20*%20from%20yahoo.finance.historicaldata%20" +
        "where%20symbol%20%3D%20%22"
        + stock + "%22%20and%20startDate%20%3D%20%22"
        + start + "%22%20and%20endDate%20%3D%20%22"
        + end + "%22&format=json&env=store%3A%2F%2F"
        + "datatables.org%2Falltableswithkeys";


    // Get the data 
     d3.json(inputURL, function (error, data) {

        data.query.results.quote.forEach(function (d) {
            d.date = parseDate(d.Date);
           //  console.log(d.date);
            d.high = +d.High;
            d.low = +d.Low;
            arr.push({
                company: stock,
                date: d.date,
                high: d.high,
                low: d.low,
                sortable: true,
                resizeable: true
            });
        });

        console.log(arr);  //returns arr with data

    });
         console.log(arr);  // returns arr[]
    };
user3359706
  • 511
  • 1
  • 5
  • 16

1 Answers1

0

d3.json is an asynchronous function, so arr would be populated only after callback is executed. You could maybe call a function after arr is populated in the callback like below:

    var dataAvailable = function() {
        console.log(arr);  
    };

    d3.json(inputURL, function (error, data) {

        data.query.results.quote.forEach(function (d) {
            d.date = parseDate(d.Date);
            //  console.log(d.date);
            d.high = +d.High;
            d.low = +d.Low;
            arr.push({
                company: stock,
                date: d.date,
                high: d.high,
                low: d.low,
                sortable: true,
                resizeable: true
            });
        });
        dataAvailable()
//        console.log(arr);  //returns arr with data

    });
Chirag Kothari
  • 1,390
  • 9
  • 19
  • The result from this is the same as first console.log and still no global array with data. Can I get the data into an external db after each iteration? – user3359706 Sep 07 '16 at 18:33
  • The answer is really no different to adding code inside the d3.json function to execute when the stock array has been fully consumed. I was looking to get the data into a globally accessible array. I will try again using a web service. Thank you – user3359706 Sep 07 '16 at 19:46