JasonBK
JasonBK

Reputation: 539

variable is undefined when attached to callback function (Javascript / Dojo)

I have this variable declared at global scope:

  var wait;

then, inside of an event listener, I assign a function to this variable, then attach a callback function: (I am using Dojo, via the ArcGIS Javascript API)

  wait = doThis();

  wait.addCallback(function (){

    doNextThing();

  });

doThis removes some layers from a map:

 doThis(){
        var layer = map.getLayer("mapLayer");
         if (layer) {
             map.removeLayer(layer);
}

..but when I run it, I get an error saying 'wait' is undefined...

I have similar syntax elsewhere in my code that works...is it because I am assigned the callback within an event listener? If so, is there a workaround? I really need doThis() to be completed before doNextThing() begins.

Upvotes: 0

Views: 392

Answers (1)

andy
andy

Reputation: 787

In JavaScript function always returns value and if you skip return keyword inside function then it returns undefined automatically. And in your doThis code there is no return statement. This is why wait gets undefined and fails on next step.

What should be returned? From shown example we can only deduce that object returned from doThis() offers addCallback function. Since ArcGIS is built upon Dojo Toolkit it is probably the Deferred object. What returns Deferred is open question having no other clues from your example.

Upvotes: 1

Related Questions