AS3:事件发生后从另一个函数返回值

时间:2014-06-05 14:35:33

标签: actionscript-3 function flash actionscript return

基本上我想检查一个用户是否存在于使用AMF的数据库中(并且效果很好!)。但后来我想将布尔值返回给另一个最初调用“checkUserExistance”函数的函数(在另一个类中)。但是,由于数据库连接不是immidiate,因此该函数将始终返回false值(即使“result”为true)。所以我想在“onUserChecked”函数中使用返回行,但这当然会给我一个错误。我以为我可以创建一个eventListener,但是,“return userExists”-line也必须在另一个函数里面,它不起作用(?)......我该怎么办?

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;
}

2 个答案:

答案 0 :(得分:1)

很抱歉,您正试图强制异步调用同步调用,这是错误的。

请参阅here

您应该学习如何以正确的方式处理事件。

我能为您提供多少帮助的是this

答案 1 :(得分:0)

这里唯一真正的答案是将userExists保存为成员变量,并在服务器返回响应时调度事件。事物的客户端应该类似于:

// 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
*/