1

I'm trying to load the text content of a file into a variable using ajax.

The function readFile() seems to works fine. I think the issue is that my file, 'countries.csv' is big and taking too long to load, so console.log(x) just returns 'undefined'

// last argument in open() is async; must be true or else chrome gives an error

function readFile(file) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', file, true);
  xhr.onreadystatechange = function () {
    if(xhr.readyState === 4 && xhr.status === 200) {
      var fileContent = xhr.responseText;
      // console.log(fileContent); <-- this line would work just fine
      return fileContent;
    }
  }
  xhr.send(null);
}


// so this next line takes some time to run
var x = readFile('/data/countries.csv');

// and this line runs before the last line is done
console.log(x);

What can I do to load the content of the file 'countries.csv' into the variable x before I start actually working with the variable x?

Am I missing some kind of event listener?

dactyrafficle
  • 838
  • 8
  • 18

1 Answers1

2

You need to pass a callback :)

Try

function readFile(file, cb) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', file, true);
  xhr.onreadystatechange = function () {
    if(xhr.readyState === 4 && xhr.status === 200) {
      var fileContent = xhr.responseText;
      return cb(fileContent);
    }
  }
  xhr.send(null);
}

readFile('/data/countries.csv', thing => console.log(thing));

Here's some extra stuff to learn more about callback/async programming in javascript: http://www.learn-js.org/en/Callbacks

The Dembinski
  • 1,469
  • 1
  • 15
  • 24
  • i looked a bit into this callback business before accepting your answer; it actually helped me resolve another pickle i'd come across (doing multiple ajax requests in one go) so this is quite exciting – dactyrafficle Mar 31 '18 at 03:13
  • It makes me extremely happy to hear that. Great stuff. :) – The Dembinski Mar 31 '18 at 03:35