I'm trying to do something exceedingly simple: write a function that reads text from a text file and returns the text in a string using AS3.
The Function
public function readData(path:String):String
{
var dataSet:String;
var urlRequest:URLRequest = new URLRequest(path);
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
urlLoader.load(urlRequest);
function urlLoader_complete(evt:Event):void {
dataSet = urlLoader.data;
trace(dataSet)
}
trace(dataSet);
return dataSet;
}
Calling the Function
var dataString:String = aq.readData("http://example.com/data.txt");
trace(dataString);
This code returns a null string when I run it. Why?
EDIT:
Ok, I now see that this doesn't work because urlLoader is acting asynchronously. I'm writing a program that reads in a data file and acts on it. Does this mean that I need to write the rest of my program inside function urlLoader_complete
? Or should I pause the program until urlLoader
is finished?