1

For some reason the code below yields unexpected behavior.

console.log(chartIntervals.length);

Displays '0' instead of the expected '10'.

console.log(chartIntervals);

Displays an array with 10 elements, and length 10.

console.log(chartIntervals[3]);

Displays 'undefined'.

I'm new to javascript. This is part of an angularJS controller. response.data.count is an integer part of a response from django API handled on another service file.

Any help would be appreciated thanks.

    var getPriceChartCounts = function(filter) {
                var savedMinPrice = filter.priceMin;
                var savedMaxPrice = filter.priceMax;
                filter.priceMin = 0;
                filter.priceMax = 100000;
                var chartIntervals = [];

                for (var i = 0; i < 10; i++) {
                    Properties.getByFilter(filter,Map.getMapBounds()).then(function(response){
                        chartIntervals.push(response.data.count);
                    });
                    filter.priceMin = filter.priceMin + 100000;
                    filter.priceMax = filter.priceMax + 100000;
                }

                filter.priceMin = savedMinPrice;
                filter.priceMax = savedMaxPrice;
                console.log(chartIntervals.length);
                console.log(chartIntervals);
                console.log(chartIntervals[3]);

                return chartIntervals;
            }

1 Answers1

1

chartIntervals is being populated asynchronously, as you can see by the .then. At the time you console.log it, the requests have only just been sent out - they haven't come back yet, so chartIntervals is still only an empty array, so its length is 0 and chartIntervals[n] for any n is undefined.

If you want your code to wait for the array to be populated before continuing, use Promise.all.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320