0

I have this function in Flash:

public function checkFile(file:String):Boolean{
                var b:Boolean;
                var responder:Responder = new Responder(function(reply:Boolean):void{
                    b=reply;
                    msg("vid_"+file+".flv "+ "exists? " + reply);
                    setState("ready");
                    status = "ready";
                },
                    function(res:Object):void{
                        trace("checkFile call failed");
                    });
                mync.call("checkFile",responder,"vid_"+file);
                return b;
            }

I can confirm that the reply variable is true, but return b ends up false:

This is the javascript I use to call the flash function:

function checkFile(){
   alert(thisMovie("vidRecorder").checkFile(currentVid));           
}

And that opens up a message box saying false, while the flash file displays true

What's going on? How can I fix it so that my function returns the same value as reply?

  • 1
    What's going on is an **asynchronous operation** – Pointy Jul 25 '13 at 19:56
  • @Pointy Oh no! That sounds ominous, especially since you put it in bold. Let me look that up. –  Jul 25 '13 at 19:59
  • 1
    The concept of async and callbacks are very well explained in [this thread](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call). – Fabrício Matté Jul 25 '13 at 20:03

1 Answers1

1

This happens because the anonymous function in your responder is executed asynchronously.

When your checkFile() function returns the value of b is still false. Eventually, your anonymous function is executed and b gets set to true ... but it's too late in this case, as your checkFile() function has already returned false.

To work around this, you might consider doing this in a slightly different fashion:

When your anonymous function is executed, have it call out to javascript with the asynchronous response. Something like this:

public function checkFile(file:String):void {
    var responder:Responder = new Responder(function(reply:Boolean):void{
        msg("vid_"+file+".flv "+ "exists? " + reply);
        setState("ready");
        status = "ready";
        ExternalInterface.call('someJavascriptFunction', reply);
    },
    function(res:Object):void{
        trace("checkFile call failed");
    });
    mync.call("checkFile",responder,"vid_"+file);
    // note we no longer return a value here
}

In the above code, we call a new Javascript function and provide it the result of the asynchronous operation.

Sunil D.
  • 17,983
  • 6
  • 53
  • 65