Question

I have a div Tag which has a OnClick Event which triggers a dojo XHR Request.

My Problem is that it will not go into the .then(lang.hitch(...)) part except if I use break points in firebug

createTS : function(){
        var container = document.createElement("div");
        console.log("Hallo World");
        xhr("getoptions.php?database=cb_content.sqlite&order=read").then(lang.hitch(this,function(result){console.og("test");this.temp = result.toString().split(";");}));
        var container = document.createElement("div");
        for(var i = 0; i< this.temp.length; i++){
                var span = document.createElement("span");
                span.setAttribute("id",this.temp[i]);
                span.innerHTML = this.temp[i];
                //on(dom.byId(this.temp[i]),"click",this.foo(span.innerHTML));
                span.setAttribute("class","apus_span_item");
                span.setAttribute("onclick","fptr('"+span.innerHTML+"');");
                container.appendChild(span);
                container.appendChild(document.createElement("br"));                            
        }
        console.log("row before return");
        return '<div>'+container.innerHTML+'</div>';
        //return this.templateString2

    },

The console tells me "Hallo World" and then it tells me that a GET Request is made and then console tells me "row before return". But the "test" won't be written.

When I make break points it will tell me test.

Anyone has the answer why it won't go into the .then?

Greetings

Was it helpful?

Solution

Except the fact that your code has errors like console.og() in stead of console.log(), your setup will never work.

You're trying to use a value that is set by an asynchronous request (that's what the XHR request is) inside synchronous code (this.temp).

So, it's very likely that the code to create your HTML (the for loop) is being executed BEFORE the XHR request has completed, and thus, before this.temp has been initialized. The reason that it works when using breakpoints is because you're delaying the HTML creation code until the XHR is completed (because you set a breakpoint).

There are two solutions here. The first one is by converting your XHR request to a synchronous request by setting the sync option to true. For more information look at the reference guide or the API documentation.

Another solution would be to make sure the code that creates your HTML is only being executed when the asynchronous request has been completed. You can do that by moving all your code that depends on this._temp inside the callback (the function inside the then() part).

However, if you need to return something from your callback, you will have to use deferreds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top