0

我是 Dojo 的新手,很难使用以下代码。我不明白为什么chartData 最后是空的。我基于 Dojo 站点上的示例创建了此方法。

代码如下:

        function(xhr, json, arrayUtil, number, Chart, theme) {

            var chartData = [];

            var def = xhr.get({
                url: "cpuusage.json",
                handleAs: "json"
            });

            def.then(function(res){
                var data = [];

                    arrayUtil.forEach(res.chart, function(chart){
                        data[chart.x] = number.parse(chart.y);
                    });
                chartData = data;
                console.info("chartData1: ", chartData);
            }, function(err){
                console.error("Failed to load JSON data");
            });

def.then 中的第一个 console.info 表示 chartData 具有正确的值。然而,当我在 def.then 方法完成后打印 chartData 的值时,它是空的。

如何确保 chartData在 def.then 调用中和之后具有相同的值。非常感谢

4

1 回答 1

2

the, methods in the xhr are all async by nature, but they return a promise. if you want to execute some code after the xhr method it should look like this:

    function(xhr, json, arrayUtil, number, Chart, theme) {

        var chartData = [];

        xhr.get({
            url: "cpuusage.json",
            handleAs: "json",
            load: function(jsonData) {
                arrayUtil.forEach(jsonData.chart, function(chart){
                    chartData[chart.x] = number.parse(chart.y);
                });
                console.info("JSON loaded from server:  ", chartData);
            },
            error: function() {
                console.error("Failed to load JSON data");
            }
        }).then(function(jsonData){
             console.info("chartData: ", chartData);
        });

by using the then function of the promise, you make sure your code executes after the AJAX call

于 2012-08-07T18:23:12.180 回答