R – ActionScript 3 AsyncToken implementation

actionscript-3asynctoken

Looking for an example or documentation links as to how to implement a method returning AsyncToken.

Note this is not about using/consuming a method returning AsyncToken! I wish to write such methods myself.

Best Answer

Implementing a method that returns an AsyncToken is simple:

function doStuffLater():AsyncToken {
    var token:AsyncToken = new AsyncToken(null);

    // This method will randomly call the responder's 'result' or 'fault'
    // handler.
    function doStuff() {
        var response:String = (Math.random() > 0.5)? "result" : "fault";
        for each (responder:IResponder in (token.responders || [])) {
            // rememeber: this is equivilent to
            // responder.result(...) or responder.fault(...)
            responder[response]("Got a result!");
        }
    }

    setTimeout(doStuff, 1000);

    return token;
}

Note that you can't actually use the applyResult and applyFault methods, because they pass the responders an Event, when the responder except the result or fault object.

Related Topic