0

I'm Beginner in Javascript. I learned python before. In javascript, I noticed that javascript runs every function with thread. Example:

$.ajax({
        url:'/',
        type:'GET',
        success:function(){
            console.log('Response Found!')
        },
        error:function(){
            console.log('Error connecting to the site.')
        },
    })

console.log('All done!')

Here a jquery ajax request and a console log function. I want to execute ajax request before console log. But the result is:
This

Console log execute before ajax request. Can any one tell how to wait till the ajax function is completed?

Shahriar
  • 71
  • 1
  • 9
  • 3
    While it's possible to run synchronous requests, it's **incredibly** bad practice and should be avoided at all costs. The better approach is to work with the async code pattern as intended. See the duplicate for how to do this. – Rory McCrossan Sep 06 '22 at 08:28
  • 1
    The "A" in "AJAX" stands for asynchronous. Not all functions in javascript run "in a new thread". Javascript is single threaded - all of your code/library code/UI updates etc all run in a single thread. The $.ajax call initiates a browser request then, when that's finished, runs the callback `success:` (etc) – freedomn-m Sep 06 '22 at 08:31

0 Answers0