Search code examples
actionscript-3for-loopwhile-loopflash-cs5urlloader

Using URLLoader.load inside a for loop



I'm creating a website using Adobe Flash Professional CS5.
I'm trying to read the content of a text file with URLLoader.load(path) inside a for loop.
The path changes every iteration.
When I trace the data from the event handler method, it returns only the last path's text file's content.
It seems like it's calling the event handler method only after the for has done looping.

CODE:

var myData:URLLoader = new URLLoader();

myData.addEventListener(Event.COMPLETE, onLoaded);

function onLoaded(e:Event):void
{
trace(myData.data);
}

for (var o = 0; o < filesArray.length; o++)
{
    for (var p = 0; p < filesArray[o].length; p++)
    {
        if (filesArray[o][p] == "category.txt")
        {
            path = "C:\\inetpub\\wwwroot\\" + filesArray[o][0] + "\\" + filesArray[o][p];
            myData.load(new URLRequest(path));
            trace(path);
        }
    }
}

This is the output:

C:\inetpub\wwwroot\0001\category.txt
C:\inetpub\wwwroot\0002\category.txt
C:\inetpub\wwwroot\0003\category.txt
C:\inetpub\wwwroot\0004\category.txt
C:\inetpub\wwwroot\0005\category.txt
Jewlery

As I said, "Jewlery" is the content of "C:\inetpub\wwwroot\0005\category.txt".

I tried to change the "onLoaded" method to return a String like this:

function onLoaded(e:Event):String
{
    return myData.data.toString();
}

That's inside the for loop:

trace(myData.load(new URLRequest(path)));

Then I got this as my output:

undefined
C:\inetpub\wwwroot\0001\category.txt
undefined
C:\inetpub\wwwroot\0002\category.txt
undefined
C:\inetpub\wwwroot\0003\category.txt
undefined
C:\inetpub\wwwroot\0004\category.txt
undefined
C:\inetpub\wwwroot\0005\category.txt

I also tried to convert the for loop to while loop, same result.
Why is it acting like that?
If URLLoader.load method doesn't work well inside a for loop, and I can do nothing about it, is there another way to read simple text from files, like FileStream or something? (I'm new to ActionScript, coming from C#)

Thanks in advance,
Freddy.


Solution

  • You are not giving your loader enough time to load your text files. Your computer is much faster than the network speed so probably even before the loader starts to load the first file it is forced to load the second than the next and so for. And the last one is the only one it has time to load.

    You have to wait until each is actually finished with loading before you start the next one. This will not work in a loop, you need to put the name in an array, then set up an index into it, initialize to the first element, start loading then in the onLoaded event get you file, increment index and go loading the next text file until you're finished.

    And yes you can use only one loader for all your files. The solution with multiple loader will also work but not because you just use multiple loader but again because each of them will not interrupt with other.