2014-02-07 137 views
0

我是dojo的新手,我試圖按特定順序指定一個變量。這裏有一個例子:dojo執行順序

require(["dojo/request"], function(request){ 
    var myVar; 

    request("helloworld.txt").then(
     function(text){ 
      myVar = text; 
      alert(myVar); //2nd alert to display and contains contents of helloworld.txt 
     }, 
      function(error){ 
      console.log("An error occurred: " + error); 
     } 

    ); 

    alert(myVar); //1st alert to display and displays undefined 
}); 

我需要myVar的了「於是」功能的內部分配,然後用它那功能之外。換句話說,我需要第一個警報來包含helloworld.txt的內容。提前致謝!

+0

的可能重複[如何返回從AJAX調用的響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) –

回答

0

確保您瞭解回調和異步代碼!這些是Javascript中絕對基本的概念,所以你可以通過閱讀它來爲你自己一個大忙。我已經解釋得比我多得多,所以我只給你留下一些鏈接(以及一種快速完成你想要的方法)。

即使你不讀這些鏈接,這裏是你必須牢記的:僅僅因爲10號線在你的JavaScript代碼來行100之前,並不意味着第10行將在行100之前運行。

Dojo的request函數返回稱爲「Promise」的內容。這個承諾允許你說「嘿,在未來,當你完成我剛剛告訴你做的事情後,運行這個功能!」 (你可以像then這樣做,就像你做的那樣)。

如果您發現這種混淆,請記住承諾在許多方面只是您在許多其他框架或腳本中看到的onSuccessonError屬性的包裝。

偉大的事情是,then也返回一個新的承諾!所以,你可以在「鏈」在一起:

require(["dojo/request"], function(request){ 
    var myVar; 

    request(
     "helloworld.txt" 
    ).then(
     function(text){ 
      myVar = text; 
      alert("First alert! " + myVar); 
     }, 
     function(error){ 
      console.log("An error occurred: " + error); 
     } 
    ).then(
     function() { 
      alert("Second alert! " + myVar); 
     } 
    ); 
}); 

承諾有其他整齊的優勢爲好,但我不會去到這裏。

+0

感謝您的回覆和信息。所以,據我瞭解,它是不可能定義一個變量內部的一個然後功能,並將其用於請求之外的任何地方。 – JoeyZ