2012-08-07 22 views
0

我是Dojo的新手,而且很難跟隨以下代碼片段。我不明白爲什麼chartData在最後是空的。我基於Dojo站點上的示例創建了此方法。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調用之後有相同的值。非常感謝

+0

我已經更新後執行我的問題基於以前的答案。 – L4zl0w 2012-08-08 09:34:23

+0

我想我現在明白了。而不是試圖在xhr之外使用chartData,然後我需要從'then'調用中啓動我的圖表,以便chartData可用。所以上面的代碼實際上是正確的,但chartData只能在'then'調用中使用。謝謝您的幫助! – L4zl0w 2012-08-08 10:12:07

回答

2

xhr中的方法本質上都是異步的,但它們會返回一個承諾。如果你想在XHR方法後執行一些代碼,它應該是這樣的:

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

使用承諾的那麼函數,你要確保你的代碼AJAX調用

+0

謝謝,但這仍然不會在xhr退出後設置chartData。有沒有可能,或者你必須'保存'的HTML節點上的數據? – L4zl0w 2012-08-07 23:52:32

+0

你的問題在於你正在處理ajax,這意味着asyncronius,並且異步方法在finalized之前退出。如果你需要chartData,你需要鏈接到另一個在xhr定稿後執行的函數,這意味着要麼使用「then」函數或調用load方法內的函數。 – 2012-08-08 00:14:15

+0

注意:設置到一個html節點將意味着你已經擁有的同樣的問題,它不會被設置的時間xhr退出 – 2012-08-08 00:17:03