0

got a little javascript problem: I have a set of to separate .js files, one acts as "class", this is my parser-"class", it basicly stores the content of a CSV file and a random part of it (csv-file is "country;capital"), parsing works fine:

var allLocations;
var rndLocations;

function CSVparser() {
this.allLocations = new Array;
this.rndLocations = new Array;

//parses the CSV into an Array ("Country;City")
this.parse = function(parser) {
    $.ajax({
        type : "GET",
        url : "ressource/capitalCountryList.txt",
        dataType : "text",
        success : function(data) {
            parser.allLocations = data.split(/\r\n|\n/);
            var min = 0;
            var max = parser.allLocations.length - 1;
            for (var i = 1; i <= 9; i++) {
                var rndIndex = (Math.floor(Math.random() * (max - min + 1) + min));
                parser.rndLocations.push(parser.allLocations[rndIndex]);
            }
        }
    });
  };
}

In my main class I now initiate a parser likes this and call the parse()-function:

var parser = new CSVparser();
parser.parse(parser);

If I now log the parser in my main class (console.log(parser)) I'm able to see the contents of the parser's properties (like for example the rndLocations array). But if I want to access this array inside of my main class via

parser.rndLocations;

the array is empty.

Whats the problem there? Sorry for my not so perfect English! Appreciate the Help!

Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
Scarysize
  • 4,131
  • 25
  • 37
  • One word: **asynchronous**. See http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call - pushing on the result data is just a *side-effect* like assigning to a variable. – user2864740 Mar 11 '14 at 22:23
  • Thanks, i now set the ajax-async property to "false". guess now it works...but thats deprecated...will look at the other solution from your link! – Scarysize Mar 11 '14 at 22:29
  • I recommend using the Promises/A callback approach for flexibility and consistency - forcing a synchronous request often runs counter to modern designs and may result in less-than-ideal user experiences. – user2864740 Mar 11 '14 at 22:30
  • Ajax should not be use as Synchronous because BLOCK complete the UI for the user and create a no pleasure interaction on the user experience. – ncubica Mar 11 '14 at 22:35

0 Answers0