0

So the for loop runs if I replace$.get('/preceed_with_an.txt', function(data){var ans = data.split('\n')}); with ans = ["filler","more filler"] but when the $.get line is in it refuses to execute the for loop and nothing is ever written to the console. For context, I am writing code that tells you if you should use A or AN before a word. Words that you use an for are all on separate lines in preceed_with_an.txt I have checked an the $.get functions and the file is written to the array just fine.

$(document).on('input',$('#givenWord'),function(){
      var ans = new Array;
      $.get('/preceed_with_an.txt', function(data){var ans = data.split('\n')});  
 for (var i = 0; i < ans.length; i++){
    console.log("help");
    if (ans[i] == $('#givenWord').lower){
      var answer = $("#answer");
      console.log("AN");
      $(answer).text("An");
      break;
    }else{
      var answer = $("#answer");
      console.log("A")
      $(answer).text("A");
    }
  }
});

1 Answers1

2

The get() is asynchronous, so ans.length is equal to zero because the data return after the for loop execution.

You have to execute the for loop in the get() callback function:

$.get(url, function(data) {
   var arr = data.split(',');
   for(...) {
      //...
   }
});

Execution flow (your code)

  1. Create ans array
  2. Call the get() function
  3. Try to execute the for loop (without available data)
  4. get() return the data

Asynchronous call

  1. Create ans array
  2. Call the get() function with the for loop in the callback
  3. get() returns data and executes the callback --> for loop with data

EXAMPLE

Check the console for the results. Even if the setTimeout function is called before the console.log(), the code continued the execution and waited for the callback's answer (after 1 second). When the result came out, the callback executed:

var def = $.Deferred();

def.done(function(data) {
  console.log(data);
});

//Asynchronus call (delays for 1 second)
setTimeout(function() { 
  def.resolve('Callback after 1 second') 
}, 1000);

//Execute immediately
console.log('Write something!');

//Console results
// 1. Write something
// 2. callback (after 1 second)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Check these links about asynchronous functions:

jQuery.get()

Async

kapantzak
  • 11,610
  • 4
  • 39
  • 61