Actionscript等待异步事件函数
问题描述:
我需要一些关于ActionScript 3中异步事件的帮助。我正在编写一个简单的类,它有两个函数,它们都返回字符串(逻辑和代码如下)。由于AS3 HTTPService的异步特性,在服务返回结果之前总是返回值行,从而产生一个空字符串。是否有可能在此函数中包含某种类型的逻辑或语句,使其在返回值之前等待响应?有没有一个框架来处理这种类型的东西?Actionscript等待异步事件函数
- 呼叫服务
- 解析JSON结果,隔离感兴趣
-
值返回值
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 }
答
你应该在你的应用程序定义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功能,在这里你将解析点,并做一些有用的东西的,或者到你的onFault功能。
BTW,你可能会遇到调用谷歌地图地理编码器这样的问题,它可能是最好使用官方的SDK,并利用他们的代码的优势:http://code.google.com/apis/maps/documentation/flash/services.html