0

When executing this get logic, it doesn't execute the lines inside until the rest of the page is loaded.

so the code hits the get... calls it. moves on to the rest of the page, then comes back and executes console.log and the internal user assignment.

why is that and how to I get it to execute that code before the rest of the page loads. I need that assignment during the remaining page load.

   $.get(userUrl, function(data, status){
        console.log ("Data: " + data + "\nStatus: " + status);
        isInternalUser=data.isInternal;

     });
Don
  • 1
  • And this code isn’t wrapped in `$(document).ready` or something similar? When you look at the network tab in the [browser console (dev tools)](https://webmasters.stackexchange.com/q/8525) (hit `F12`), can you confirm that there is no network activity for `userUrl` until the page is loaded? – Sebastian Simon Jul 17 '19 at 20:49
  • 1
    This is by design; it's how asynchronous code works. – Rory McCrossan Jul 17 '19 at 20:54
  • I watched and confirmed that the GET call was in a pending state until the rest of the page had loaded..... – Don Jul 17 '19 at 21:04
  • also, I am not using .ajax... I am doing a straight Jquery get... but I think I can safely assume it is working the same way. Will try the ajax asynch flag yet. – Don Jul 17 '19 at 21:24

1 Answers1

0

This is how asynchronous code works. AJAX sends the request to the server, but it doesn't wait for the response to be received, it continues executing the rest of the code. When the browser receives the response, it puts it on the event queue, but this is processed in order. If there are other events that were triggered first, their listeners will be executed in order.

AJAX does have the option to operate synchronously; in jQuery, you can access this by using $.ajax and using the async: false option. But this feature is deprecated, so you really should try to design your application so it doesn't need it.

See How do I return the response from an asynchronous call? and Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Barmar
  • 741,623
  • 53
  • 500
  • 612