Reputation: 27125
In the following code, is doThisFirst()
guaranteed to execute before doThisSecond()
?
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() :
new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
doThisSecond(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "/myscript.php?", true);
xmlhttp.send();
doThisFirst();
If not, how can I guarantee this execution order (aside from the naive solution of setting a flag at the end of doThisFirst()
and then polling while(!flag);
before executing doThisSecond()
)?. I'm looking for a pure-Javascript solution (no jquery).
Important note: I do not want to execute the AJAX request synchronously, which would execute doThisSecond()
before doThisFirst()
.
Upvotes: 1
Views: 767
Reputation: 179256
doThisFirst()
will execute synchronously after xmlhttp.send
, and xmlhttp.onreadystatechange
cannot be executed until the control flow has released back to the "Event Loop".
There is one catch. It may be possible* that the callback is executed as part of .send()
, in which case doThisSecond
would be executed first because the code never needed to release to the event loop. If you need to enforce an asynchronous behavior, simply wrapping doThisSecond
as setTimeout(function () { doThisSecond(xmlhttp.response.Text) }, 1)
will enforce that the function can not be called until the flow control is released to the event loop.
In your example it shouldn't make a difference, as I'm fairly certain that onreadystatechange
is always called after the release to the event loop (synchronous XHR notwithstanding).
* whether by set to execute the AJAX call in a synchronous blocking manner, or due to caching, I honestly don't know enough of the XHR nuances cross-browser
Upvotes: 3