3

I'm wondering if anyone can help me understand some asynchronous javascript concepts...

Say I make an asynch ajax call like so:

  xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange= myFoo;
  xmlhttp.open("GET",url,true);

Here is my callback function:

function myFoo()
{
if (xmlhttp.readyState==4)
  {
  if (xmlhttp.status==200)
    {
    // Success message
    }
  else
    {
    // some error message
    }
  }
}

Now, where and when does the execution path start again? Once I make the call to open(), does execution continue directly below the open() and another "thread" enters the asynch function once the ajax request has been completed?

Or, does the browser wait for the request to complete, make the Asynch call, and then execution continues right after the open?

Thanks!

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
DigitalZebra
  • 39,494
  • 39
  • 114
  • 146
  • Does this answer your question? [Does an asynchronous call always create/call a new thread?](https://stackoverflow.com/questions/598436/does-an-asynchronous-call-always-create-call-a-new-thread) – desertnaut Jun 01 '20 at 01:59

1 Answers1

1

First, you are missing a xmlhttp.send call.

The browser doesnt wait for the request to complete to continue after the open. That is the entire idea behing a async call.

Rajat
  • 32,970
  • 17
  • 67
  • 87
  • Yeah I realize that... I guess it makes more sense to me in other languages because an asynchronous call is usually coming in as another thread... so I guess we have multithreaded javascript? – DigitalZebra Mar 31 '10 at 22:47
  • 1
    Nope, JavaScript is not multithreaded. The workers API is a latest addition that allows bending of rules but its fairly new. To wrap your head around what happens when the response comes back, read this link : http://www.javascriptkata.com/2007/06/12/ajax-javascript-and-threads-the-final-truth/ – Rajat Mar 31 '10 at 23:17
  • I'm obviously not too familiar with asynch ways lol... thanks for the link – DigitalZebra Mar 31 '10 at 23:20