2010
03.18

It took me forever to finally figure out what to do with asynctoken in Flex 3, so I thought I would give you the jist of what I found out.

Asynctokens allow Flex to wait for an event to happen. Basically.

So if you have a PHP script that takes a bit longer, it tells Flex to wait till it’s done and THEN call the next set of instructions.

So we first import the Asynctoken and AsyncResponder libraries.

import mx.rpc.AsyncToken;
import mx.rpc.AsyncResponder;

Then we need to make a public var for our token.

public var tok:AsyncToken = new AsyncToken(null);

Now we make our main function that will use the token. In this exaxmple, we’ll use a simple login.

private function checkLogin():void {

var tok:AsyncToken = amfcall.checkLogin(username.text, password.text);

tok.addResponder(new AsyncResponder(loginwin, loginfail, tok));

}

amfcall.checkLogin() is our PHP function that we are calling.

With tokaddResponder, you call 2 other functions. one for the script working correctly, the other for something going wrong, along with the token with the information.

Next we make the two functions, and pass ResultEvent, FaultEvent (for either the fail or succeed), and the token itself.

//IF THE LOGIN QUERY IS OKAY AND PHP HAD NO SYNTAX ERRORS, ETC.

public function loginwin(event:ResultEvent, token:AsyncToken):void{

if(event.result == “true”){

Alert.show(“HUZZAH!”);

}

else{

Alert.show(“Wrong User/Pass combo”); }

}

//IF THERE ARE SYNTAX/DATABASE ERRORS

public function loginfail(event:FaultEvent, token:AsyncToken):void{

Alert.show(“Uh oh, something went wrong!”);

}

event.result is the string returning from the PHP Script (ex. return “true”;)

Anyways, you can use the set of events for any AMFPHP call (from what I’ve done anyways) and it works great.

Let me know if you have any questions or comments about this.

7 comments so far

Add Your Comment
  1. wow! i came here just by creeping your face book and turns out… this is exactly what i needed. Thanks a bunch! keep up the sick tutorials.

  2. Hi Adam,

    Good article. It helped me lot for AsyncToken.

    Thanks a lot.

  3. Great! thanks it really helped me and it saved me from two full days of funny debugging!

    Alejandro

  4. So.. why asynchtoken versus eventlistener approach. pros/cons?

  5. I have more than one calls like this and I have to wait for all token results to do something more. How can I do this ? or How can I wait for each token results ?

  6. The “public var” is completely superfluous in your example.

  7. thank you! keep up the good work