Chartjs-Ajax asynchronicity calls end function before inner loop function

1đź‘Ť

It is working exactly as it should because the “pushed something” code is in a NESTED AJAX request’s done callback. That will be sometime in the future. And so, the JavaScript engine continues on processing the rest of the code, which includes “Drawed something” in the top-level AJAX request next, so that happens.

At some point in the future, the AJAX call will complete and the done callback will fire and then you will get “pushed something”.

// 1. When the document is ready...
$(document).ready(function () {
    var dataSets = [];

    // 2. Make the AJAX call, BUT DONE RUN .done YET!
    getSensorIDs().done(function (result) {

        var sensorIDs = jQuery.parseJSON(result);

        // loop through each id
        $.each(sensorIDs, function (index, value) { 

            // 3. As part of the first AJAX call, make a SECOND one
            getDataBySensorID(value.id).done(function (res) {
                var temperatureData = jQuery.parseJSON(res);
                var dataPoints = [];
                $.each(temperatureData, function (index, value) {
                    dataPoints.push({
                        x: index
                        , y: value.value
                    });
                }); 

                // 5. The nested call finishes last
                dataSets.push(buildDataset(dataPoints, 1));
                alert("Pushed something.");

            });  

        });

        // 4. This runs first because the first AJAX call is finishing 
        // before the nested one (above)
        alert("Drawed something.");
        drawChart(dataSets);

    });  

});

Leave a comment