In you application you have multiple service calls happening at the same time and you need to know which data coming back belongs to which call.
Using ASyncToken we can add a variable to the call to identify it.
mx.rpc.ASyncToken is a dynamic class meaning we can add properties and methods to it at runtime. The documantation states that it is 'a place to set additional or token-level data for asynchronous rpc operations'.
As an example, we have an application with a DateChooser control in it. Everytime the user scrolls to a new month we need to retrieve an xml file from the server for that month. Since there is no way to garantee which order these files will come back in we need a way to identify them. Using ASyncToken we can add an identifying property to the result event that is returned by the service call.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
<mx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.AsyncToken;
import mx.events.DateChooserEvent;
private function scrollHandler(event:DateChooserEvent):void
{
var month:int = event.currentTarget.displayedMonth;
var monthName:String = event.currentTarget.monthNames[month];
service.url = "xml/"+monthName+".xml";
var token:AsyncToken = service.send();
token.resultHandler = onResult;
token.faultHandler = onFault;
token.month = monthName;
}
private function onResult(event:ResultEvent):void
{
resultText.text = "MonthName: "+event.token.month+"\n\n";
resultText.text += "Result: "+event.result.data.month;
}
private function onFault(event:FaultEvent):void
{
resultText.text = event.fault.faultString;
}
]]>
</mx:Script>
<mx:HTTPService id="service" result="event.token.resultHandler(event)" fault="event.token.faultHandler(event)"/>
<mx:DateChooser id="dateChooser" scroll="scrollHandler(event)"/>
<mx:TextArea id="resultText" width="300" height="200"/>
</mx:Application>
In the above code, when the scrollHandler event is called we are going to retrieve an xml file from the server. If the user clicks fast enough we could have multiple requests happening at the same time. In HTPPService the send method returns an ASyncToken so we will access this and add a property to identify the month that the returned data belongs to. ResultEvent's have a property called token so we can access our month property through this in the result handler.
This method can also be used with WebService and RemoteObject calls. In these calls the operation or method that is called returns the ASyncToken.
Example: var token : AsyncToken = service.login( loginVO );
I have attached the source files for the sample code.