title: JavaScript random item from an imported array behaving strangely
body: <p>The following code seems to be behaving strangely.  Basically, I'm importing a list of line-separated sentences from a text file, then making an array out of them.  But when I try to choose a random sentence from the array, it doesn't work because sentenceString becomes undefined.</p>
  
  <p>However, when I run 
  Math.floor(Math.random() * (sentenceArr.length) + 1);
  I get a nice random number as expected.</p>
  
  <p>And when I run sentenceArr.length
  I get the number 12, which is indeed the length.</p>
  
  <p>What am I missing?</p>
  
  <pre><code>    var sentenceArr = [];
  
      $.get('sentences.txt', function(data){
          sentenceArr = data.split('\n');
      });
  
      var rand = Math.floor(Math.random() * (sentenceArr.length) + 1);
  
      var sentenceString = sentenceArr[rand];
  
      var sentence = sentenceString.split(' ');
  </code></pre>
  
  <p>Update:
  I tried making a Promise as suggested below, but it still doesn't seem to be working.  My new code with the Promise looks like this:</p>
  
  <pre><code>    var sentenceArr = [];
      var done = false;
  
      function loadSentences() {
          var rand = Math.floor(Math.random() * (sentenceArr.length) + 1);
          var sentenceString = sentenceArr[rand];
          var sentence = sentenceString.split(' ');
      };
  
      $.get('/sentences.txt', function(data){
          sentenceArr = data.split('\n');
          done = true;
      });     
  
      var isItDone = new Promise(function(resolve) {
          if(done) {  
              resolve('it worked');
          }   
      });
  
      //consume the promise:
      var checkIfDone = function() {
          isItDone
              .then(function (fulfilled) {
                  loadSentences();        
              })
  
              .catch(function (error) {
                  console.log('oops, it failed');
              });
      };
  
      checkIfDone();
  </code></pre>
  
  <p>This seems to always return "oops, it failed", as if the promise is never fulfilled.  However, when I check the value of "done", it is "true", meaning the Ajax request was completed before moving on to the next steps.  Could anyone enlighten me?  I've read three tutorials on promises already, and can't seem to figure out my error in applying the concept to my own code.  Thank you.</p>