Handling asynchronous calls can be a pain. When we make a call like load() there is really only two thing that can happen we get success or failed. For 90% of applications that’s all we need. The native flash API is unwieldy and messy and overly complex.

I was using something I was calling a fluent responder but it was pointed that this is similar to the JS design pattern promises. There is a javascript proposal here and a nice JS implementation here and Shaun’s as3 version here promises.

I’ve since tweaked my implementations to be more true to these versions but with the focus on making it simple to use in as3. I’ve called it a pledge to differentiate and the code is on github here on github.

Ok so what is it. Basically I simple way of handling asynchronous calls in a nice clean manner. Here is what a using a file loader looks like using a pledges.

    public function Example() {
        var loader:FileLoader = new FileLoader();
        loader.load("http://www.w3schools.com/xml/note.xml").then(successHandler,errorHandler,progressHandler);
    }

    private function successHandler(event:Event):void{
        var xml:XML = XML( event.target.data);
        trace("Success");
        trace(xml);
    }

    private function errorHandler(event:IOErrorEvent):void{
        trace("FAIL!");
    }

    private function progressHandler(event:ProgressEvent):void{
        trace("loaded:" + event.bytesLoaded + " of total: " + event.bytesTotal);
    }

So the call load() is returning a pledge object to which we can add our handlers. Its very simple we can added as many handlers of either type as we want or none at all. There is no garbage collection worry about because as soon as success or failuer is triggered its automatically cleaned up. We can also pass the pledge around if we need to.

So to create a class that makes a pledge our loader now look like this

 public function load(url:String):IPledge{
        var pledge:Pledge = new Pledge();
        var request:URLRequest = new URLRequest(url);
        var loader:URLLoader = new URLLoader();
        pledge.mapSuccessEvent(loader,Event.COMPLETE);
        pledge.mapFailureEvent(loader,IOErrorEvent.IO_ERROR);
        pledge.mapProgressEvent(loader,ProgressEvent.PROGRESS);
        loader.load(request);
        return pledge;
    }

The first thing to note is the return type is IPledge which gives our listener the ability to add handlers but not to trigger the pledge them selves. We then create our new Pledge object. Next we set up the loader and map the native as3 loader events to it. Finally we call load. You can use this for almost any asynchronous calls. Progress updates are optional.
That’s it, dead easy.

 

Comments are closed.