Hank Rearden Hank Rearden - 5 months ago 21
Javascript Question

Wait for asyn call to finish - too late

I have a dialog with a button. Once clicked the button calls an async method which returns true or false depending on whether the posted data is valid or not.
The click event calls the method below.
Now, the problem is that closeDialog is called before the callback function is executed!!
How can I make this work?

Thanks

close: function (srcCmd) {
var closeResult = true;
asyncThing(function(result) {
if (result)
closeResult = true;
else
closeResult = false;
});

if (closeResult !== false) {
this.closeDialog();
}
},

Answer

The function withing asyncThing is called when(whenever that might be) the asynchronous call is finished. So this will not be interpreted line-by-line.

Move the latter if question to callback function and it will be fine.

close: function (srcCmd) {
   var closeResult = true;
   asyncThing(function(result) {
       if (result)
           closeResult = true;
       else
           closeResult = false;
    if (closeResult !== false) {
       this.closeDialog();
    }
  });
},