Ajax异步性在内循环函数之前调用end函数

时间:2016-12-13 22:04:27

标签: javascript jquery ajax chart.js

这是我正在努力的代码:

$(document).ready(function () {
    var dataSets = [];
    getSensorIDs().done(function (result) {
        var sensorIDs = jQuery.parseJSON(result);
        $.each(sensorIDs, function (index, value) { //loop through each id
            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
                    });
                })
                dataSets.push(buildDataset(dataPoints, 1));
                alert("Pushed something.");
            });
        });
        alert("Drawed something.");
        drawChart(dataSets);
    })
});

问题是:Drawed something发生在Pushed something之前,即使程序流不喜欢它。我以为我用problem修复了ajax的.done()(它的异步),但它看起来并非如此。什么是这个问题的正确解决方案?

1 个答案:

答案 0 :(得分:1)

它完全正常工作,因为"推动了一些东西"代码位于 NESTED AJAX请求的done回调中。这将是未来的某个时候。因此,JavaScript引擎继续处理剩余的代码,其中包括" Drawed something"在接下来的顶级AJAX请求中,这样就发生了。

在将来的某个时刻,AJAX调用将完成,done回调将会触发,然后你会得到一些东西"。

// 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);

    });  

});