1

I am trying to set a global variable (citiesJSON) inside an asynchronous function that reads the contents of a file, but I don't know how to implement the callback location to do so. Below is my code:

var citiesJSON = "";
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);

    rawFile.onreadystatechange = function () {
        console.log("rawFile.readyState = " + rawFile.readyState);
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                citiesJSON = rawFile.responseText;
            }
        }
    }
    rawFile.send(null);
}

readTextFile("testfile.txt");
Henry Zhu
  • 2,488
  • 9
  • 43
  • 87

0 Answers0