Actionscript等待函数内的异步事件

时间:2009-11-16 21:02:42

标签: actionscript-3 asynchronous wait

我需要在ActionScript 3中对异步事件提供一点帮助。我正在编写一个包含两个函数的简单类,这两个函数都返回字符串(逻辑和代码如下所示)。由于AS3 HTTPService的异步特性,在从服务返回结果之前始终会达到返回值行,从而产生空字符串。是否可以在此函数中包含某种类型的逻辑或语句,使其在返回值之前等待响应?是否有一个框架来处理这类东西?

  1. 致电服务
  2. 解析JSON结果,隔离感兴趣的值
  3. 返回值

    public function geocodeLocation(address:String):Point
    {
        //call Google Maps API Geocode service directly over HTTP
        var httpService:HTTPService = new HTTPService;
        httpService.useProxy = false;
        httpService.url = //"URL WILL GO HERE";
        httpService.method = HTTPRequestMessage.GET_METHOD;
        var asyncToken : AsyncToken = httpService.send();
        asyncToken.addResponder( new AsyncResponder( onResult, onFault));
    
        function onResult( e : ResultEvent, token : Object = null ) : void
        {
            //parse JSON and get value, logic not implemented yet
            var jsonValue:String=""
        }
    
        function onFault( info : Object, token : Object = null ) : void
        {
            Alert.show(info.toString());
        }
    
        return jsonValue; //line reached before onResult fires
    }
    

1 个答案:

答案 0 :(得分:2)

您应该在应用程序中定义onResult和onFault - 无论您在何处调用geocodeLocation - 然后将它们作为地址后的参数传递给您的函数。您的onResult函数将接收数据,解析Point并对其执行某些操作。您的geocodeLocation函数不会返回任何内容。

public function geocodeLocation(address:String, onResult:Function, onFault:Function):void
{
    //call Google Maps API Geocode service directly over HTTP
    var httpService:HTTPService = new HTTPService;
    httpService.useProxy = false;
    httpService.url = //"URL WILL GO HERE";
    httpService.method = HTTPRequestMessage.GET_METHOD;
    var asyncToken : AsyncToken = httpService.send();
    asyncToken.addResponder( new AsyncResponder( onResult, onFault));
}

然后在你的应用程序的某个地方:

function onResult( e : ResultEvent, token : Object = null ) : void
{
    var jsonValue:String=""
    //parse JSON and get value, logic not implemented yet
    var point:Point = new Point();
    //do something with point
}

function onFault( info : Object, token : Object = null ) : void
{
    Alert.show(info.toString());
    //sad face
}

var address:String = "your address here";
geocodeLocation(address, onResult, onFault);

当Web服务响应时,控件将传递给你的onResult函数,在那里你将解析Point并对它做一些有用的事情,或者你的onFault函数。

顺便说一句,您可能会遇到以这种方式调用Google Maps地理编码器的问题,最好使用官方SDK并利用他们的代码:http://code.google.com/apis/maps/documentation/flash/services.html