When Flash makes a request for data from an external source, that operation is asynchronous. The most basic explanation of what this means is that the data loads "in the background" and triggers the event handler you allocate to Event.COMPLETE
when it is received. This can happen at any point in the lifetime of your application.
Your data WILL NOT be available immediately after calling load()
on your URLLoader
. You must attach an event listener for Event.COMPLETE
and interact with the response there.
var request:URLRequest = new URLRequest('http://someservice.com');
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, responseReceived);
loader.load(request);
trace(loader.data); // Will be null.
function responseReceived(event:Event):void {
trace(loader.data); // Will be populated with the server response.
}
trace(loader.data); // Will still be null.
You cannot get around this with any little tricks like using setTimeout
or similar:
setTimeout(function() {
trace(loader.data); // Will be null if the data hasn't finished loading
// after 1000ms (which you can't guarantee).
}, 1000);