Jeff Kyzer Jeff Kyzer - 1 year ago 74
Javascript Question

jquery .get return odd results

I am reading in a text file using jquery $.get. I have the following code.

console.log("before the get");
$.get("testfile.txt", function(data){
console.log("in the get");
console.log(data);
});
console.log("after the get");


In the console, I would expect to see

before the get
in the get
'...the data...'
after the get


Instead, I am getting

before the get
after the get
in the get
'...the data...'


Why am I getting the odd order? Thank you.

Answer Source

It is not odd. That's normal because the get request is async. The other codes oafter get call won't wait for the completion of get and continues execution.

You have to print the console log message after completion of the get call.

console.log("before the get");
$.get("testfile.txt", function(data){
   console.log("in the get");
   console.log(data);
   console.log("after the get");
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download