2014-02-07 140 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