MartinMo
MartinMo

Reputation: 17

AS3: Returning value from another function after event happened

Basically I want to check if a user exists in a database using AMF (and that works great!). But then I want to return the boolean value to another function (in another class) that originally called the "checkUserExistance" function. But, since the database connection isn't immidiate, this function will always return a false value (even if "result" is true). So I would like to have the return-line inside the "onUserChecked"-function but that of course gives me an error. I thought I could create an eventListener, but then, the "return userExists"-line would also have to be inside another function, which doesnät work(?)... What can I do?

public function checkUserExistance(username:String) {
    var responderBOOLEAN:Responder = new Responder(onUserChecked, onFault)
    var userExists:Boolean = false;
    connection.connect(gateway);
    connection.call("User.checkUser", responderBOOLEAN, username);
    connection.close();
    function onUserChecked(result:Boolean):void {
        userExists = result;
    }
    return userExists;
}

Upvotes: 0

Views: 261

Answers (2)

Andrey Popov
Andrey Popov

Reputation: 7520

The only true answer here is to save userExists as a member variable, and dispatch event when the server returns you a response. The client side of the things should be similar to:

// add listener, ServerEvent is a custom event (see below)
server.addEventListener(ServerEvent.CHECK_RESPONSE, onCheckResponse);
server.checkUserExistance('username'); // start the query

function onCheckResponse(e:ServerEvent):void {
    if (e.userExists) {
    }
}


// inside server class
function onUserChecked(result:Boolean):void {
   userExists = true;
   dispatchEvent(new ServerEvent(ServerEvent.CHECK_RESPONSE, userExists));
}

/* ServerEvent is a custom class that extens Event
   Such classes are used so you can pass special properties in them
   via constructor (pass data, store it into member variable)
   and through getter for that variable.

   If you don't like it, simply add/dispatch Event.COMPLETE
   and use public property to get userExists from server
*/

Upvotes: 0

SharpEdge
SharpEdge

Reputation: 1762

I'm sorry but you are trying to force an Asynchronous call to a Synchronous one and this is WRONG.

See here

You should learn how to handle events in the correct way.

What can i suggest you that helped me a lot is this

Upvotes: 1

Related Questions