Search code examples
functionactionscript-3urlloader

as3 return value on loader complete


I am trying to get my function to return a value from a php script once it has loaded. I am having issues with the 'return' aspect. Trying to the the value of 'TheLink" from a function with a 'return' in it. It's usually null. What am I doing wrong here?

var theLink = loadAudio();

public function loadAudio():String
  {
  var req:URLRequest = new URLRequest("myScript.php");
  var loader:URLLoader = new URLLoader(req);
  loader.dataFormat = URLLoaderDataFormat.VARIABLES;
  loader.addEventListener(Event.COMPLETE, Finished);

    function Finished(e:Event)
      {                 
      var theValue = JSON.parse(e.target.data.audioLink);
      return theValue;
      }                     
   }

Solution

  • A lot of things are wrong in your code but more important is that you cannot escape the asynchronous nature of AS3.

    First thing first, even if AS3 wasn't asynchronous your code would still not work. The "loadAudio" never returns anything so theLink can never get any data. The 'Finished' method is the one return something but there's no variable to catch that data either.

    Now the real stuff, AS3 is asynchronous that means that things will happen at a later time and this is why you need to pass an event listener in order to 'catch' when things happen. In your case the Event.COMPLETE will trigger at a later time (asynchronous) so there's no way for a variable to catch the result before the result is actually available so:

    var theLink:Object = loadAudio();//this is not possible
    

    The correct way is:

    private var loader:URLLoader;//avoid GC
    private var theLink:Object;//this will store result when available
    
    //I assume you are using a class
    public function MyClass()
    {
        loadAudio();//let's start loading stuff
    }
    
    private function loadAudio():void
    {
       var req:URLRequest = new URLRequest("myScript.php");
       loader = new URLLoader();
       loader.dataFormat = URLLoaderDataFormat.VARIABLES;
       loader.addEventListener(Event.COMPLETE, handleLoaded);
       loader.load(req);
    }
    
    private function handleLoaded(e:Event):void
    {                 
        theLink = JSON.parse(e.target.data.audioLink);   
        //done loading so store results.   
    }