Javascript dojo执行顺序
我是dojo新手,我正在尝试按特定顺序分配变量。以下是一个例子:Javascript dojo执行顺序,javascript,dojo,Javascript,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 content
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
});
我需要在“.then”函数内部分配myVar,然后在该函数外部使用它。换句话说,我需要第一个警报来包含helloworld.txt的内容。提前谢谢 确保您理解回调和异步代码!这些都是Javascript中绝对基本的概念,因此您可以通过阅读它来帮自己一个大忙 它已经被解释得比我好多次了,所以我只给你留下一些链接(和一个快速实现你想要的东西的方法)
请求
函数返回一个称为“承诺”的东西。承诺允许您说“嘿,将来,在完成我刚才告诉您的操作后,运行此函数!”(您可以使用然后函数执行此操作,就像您所做的那样)
如果您感到困惑,请记住承诺在很多方面只是在许多其他框架或脚本中看到的onSuccess
或onError
属性的包装
最棒的是,然后
也会返回一个新的承诺!因此,您可以将它们“链接”在一起:
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);
}
);
});
承诺还有其他好处,但我不在此赘述。感谢您的回复和信息。因此,据我所知,不可能在then函数中定义一个变量,并在请求之外的任何地方使用它。