Avg. Rating 5.0

Problem

You need to make multiple requests for data, but each request depends on data retrieved from the previous request, so they cannot be run at the same time.

Solution

Store your requests in an array, calling them pseudo-recursively as each request is finished.

Detailed explanation

Rather than creating new URLRequests that run asynchonously within your loop, use the loop to populate an array with the locations of your requests.

var requestQueue:Array = [];
var i:int = 0;
var size:int = 5;

for (i = 0; i < size; i++) {
    requestQueue.push('myXML_version' + i + '.xml');
}

Now that we have these locations stored, we can use recursion to load them one at a time.

var xmlLoader:URLLoader;
xmlLoader.addEventListener(Event.COMPLETE, onXMLDataLoadComplete);

function loadNextXML():void {
    
    // Get the first request location that was added.
    // This will later be removed from the array once 
    // it has successfully loaded.
    var location:String = requestQueue[0];
    
    // Send out the request to load the data
    xmlLoader.load(new URLRequest(location));
    
}

function onXMLDataLoadComplete(e:Event):void {
    
    // Remove the first item (at index of 0) in the array
    requestQueue.splice(0, 1);
    
    /* Insert your code for processing the data here */
    
    // If there are still items remaining in the queue, 
    // load the next one. Otherwise, notify application 
    // that all files have been loaded.
    if (requestQueue.length > 0) {
        loadNextXML();
    }
    else {
        trace('All files have been loaded!');
    }
    
}

Remember that loading multiple files one after the other can take some time-don't forget to visually inform your users that data is processing in the background!


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes