0

I am new to dojo and I am trying to assign a variable in a specific order. Here is an example:

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

I need myVar to be assigned inside of the ".then" function and then use it outside of that function. In other words, I need the 1st alert to contain the contents of helloworld.txt. Thanks in advance!

1

1 Answer 1

0

Make sure you understand callbacks and asynchronous code! These are absolutely fundamental concepts in Javascript, so you'll do yourself a big favor by reading up on it.

It has been explained far better than I could many many times, so I'll just leave you with some links (and a quick way to accomplish what you want).

Even if you don't read those links, here's what you have to keep in mind: Just because line 10 comes before line 100 in your Javascript code, doesn't mean line 10 will run before line 100.

Dojo's request function returns something called a "Promise". The promise allows you to say "Hey, in the future, after you're done with what I just told you to do, run this function!" (you do this with the then function, like you've done).

If you find this confusing, remember that promises are in many ways just a wrapper around the onSuccess or onError attributes you see in many other frameworks or scripts.

The great thing is that then also returns a new promise! So you can "chain" them together:

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

Promises have other neat advantages as well, but I wont go into that here.

1
  • Thanks for the response and the info. So as I understand it, it is impossible to define a variable inside of a then function and use it any where outside of the request.
    – JoeyZ
    Feb 10, 2014 at 21:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.