0

Down below is a part of a program that I have issues with. Im getting a random word from a text-file thats separated by linebreaks and that separates the word in character arrays. Everything works fine within the function but it doesnt work on the global level. What do i do wrong? Thanks a bunch!

function getRandom(min, max) {
  return Math.trunc(Math.random() * (max - min) + min);
}

var txtFile = new XMLHttpRequest();
txtFile.open("GET", "database.txt", true);
txtFile.onreadystatechange = async function () {
  if (txtFile.readyState === 4) {
    // Makes sure the document is ready to parse.
    if (txtFile.status === 200) {
      // Makes sure it's found the file.
      allText = txtFile.responseText;
      lines = txtFile.responseText.split("\n"); // Will separate each line into an array

      word = getRandom(1, lines.length);
      letters = lines[word];
      console.log(letters);

      arrLetters = "";
      arrLetters = letters.split("");
      arrLetters.pop();

      console.log(arrLetters);
    }
  }
};

txtFile.send(null);
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
Omninode
  • 13
  • 7
  • Where is the `arrLetters` defined from? You should define it from the global scope. Also, you should always define your variables with `var` or `let`. – Kubwimana Adrien Dec 10 '20 at 04:52

1 Answers1

0

I presume by global scope, you're referring to the following:

txtFile.onreadystatechange = async function () {
  // handler where you set arrLetters to some value
};

txtFile.send(null);

// <-- are you trying to use arrLetters at this place?

If the previous assumption is correct, then you're falling into a common misunderstanding that newbies have when they start trying to work with async logic. The reason why you can't access arrLetters at that place is simply because arrLetters doesn't exist yet. That code with the <-- is actually getting run before your onreadystatechange function gets called. Any code that needs to use arrLetters has to be placed inside your onreadystatechange function. If you feel like that function is getting too large, then just break it into smaller functions and call them from onreadystatechange.

Let me know if I'm interpreting this question correctly, or if you were actually trying to do something else. If you were actually trying to do something else, could you edit your question and add the code snippet that you think should work but doesn't, so that we can better explain why it doesn't work.

Scotty Jamison
  • 10,498
  • 2
  • 24
  • 30