Javascript - get contents of txt file

Hi everyone, I’m facing some few problems with my javascript code, as to my understanding probably related to asynchronous functions.

I have some large txt files that I want to import in my javascript code, everything is under the same domain.
For instance, when I open /index.php I want Javascript to load text from several text files located in: /log/ip_number/log.txt

At the moment I’m using something like this:

for (var i = 0; i < numberOfVPS; i++) {
    $.get("/log/"+ip_list[i]+"/log.txt", function(contents){
     //does my things with contents
     array.push(myOutput)
     });
}

at the end of the code, I should get an array ordered by the order of IPs in the ip_list array… but that’s not what I get and I can’t really understand why…

For example, I should get:
array = [1, 2, 3, 4, 5]
where 1, 2, 3, 4 and 5 are related to ip_list[0], ip_list[1], ip_list[2], ip_list[3], ip_list[4],
but I get something like:
array = [2, 5, 3, 1, 4], and everytime I reload the page there is a different order…
I think that’s due to the fact that the javascript code didn’t manage to load the text files and thus give me some unordered output, but that’s just my opinion, the opinion of a newbie “programmer”…

Please help me with that!
Jerry

I think it’s because you are basically making asynchronous calls with a callback to a function that push the data onto the array. These callbacks will trigger when the data is retrieved which might happen out of order especially if the logs are of differing sizes.

I would suggest attempting to do this in some sort of blocking way, synchronous manner, or wrap the output in objects that contain identifying information for each IP that you can attach the log data to and then operate on, and push those objects onto an array.

@CurtGreen made the correct diagnosis. Take a look at $.when in the jquery docs

var promises = []
for (...) {
    promises.push($.get(...)) // no callback here
}
$.when.apply(null, promises).then(function() {...} // args in callback will be in order

jquery is quirky with the way results are returned, it varies based on if only one arg or multiple, but that is another story, see example. But I think it is best to wrap a standard xhr in a promise and use that.

Can’t really tell why but

var files = [];
for( var n = 0; n < numberOfVPS; n++ ) { 
    files[n] = $.get("FILEPATH")
});

seems to works even without

$.when...

I resolved using this!
Thanks everyone! I’ve managed to understand the problem, I should dive in promises a lot more…

1 Like