3

The following block of code successfully returns array values (No. 1 130879253000, 34756)

    function getCsv(file_name){
        var array_holder = [];
        $.get(file_name, function(csv, state, xhr) {

            // inconsistency
            if (typeof csv != 'string') {
                csv = xhr.responseText;
            }

            // parse the CSV trades
            var header, comment = /^#/, x;

            $.each(csv.split('\n'), function(i, line){
                if (!comment.test(line)) {
                    if (!header) {
                        header = line;
                    }
                    else {
                        var point = line.split(';'),
                            date = point[0].split('-'),
                            time = point[1].split(':');

                        if (point.length > 1) {
                            x = Date.UTC(date[2], date[1] - 1, date[0], time[2], time[1], time[0]);

                            array_holder.push([
                                x, // time
                                parseFloat(point[2]) // close
                            ]);
                        }
                    }
                }

            }); // each
            alert('No. 1' + array_holder[0]);
        });
        return array_holder;
    }

In the following section of code, I'm trying to call getCsv but I get No. 2 undefined

$(function() {

        var trades  = getCsv('trades.csv');
        var spreads = getCsv('spreads.csv');
        alert('No. 2' + trades[0]);
}

Why are my arrays not getting populated? In the actual code I have the above two functions right next to each other in the order listed here. So the files are getting read correctly it's as if array_holder falls out of scope and gets garbage collected.

deltanovember
  • 42,611
  • 64
  • 162
  • 244

2 Answers2

9

This is due to the asynchronous nature of $.get(). At the point where you do the alert, the AJAX request has not necessarily run yet.

Do the alerting in the request's success callback, where the "No.1" alert takes place.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
2

$.get() is asynchronous. So the function you're writing as a second argument is not called untill file is loaded, and then the return from your getCsv function is reached before your succes function executes, that's why the array is empty. Refer to this discussion's answers to get a solution :
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Community
  • 1
  • 1
psycho
  • 631
  • 10
  • 27