Ajax's send Synchronize problem

 var xhr = new XMLHttpRequest();
    xhr.open("get","1.html",false);
    xhr.onreadystatechange = function () {
        console.log(xhr.readyState)
    }
    xhr.send();

Why can Synchronize only output 4? asynchronous task queue. I know you can output 2d3 onreadystatechange 4, but Synchronize doesn"t add tasks to the task queue. But the difference between Synchronize and async is that it waits here, and onreadystatechange triggers while waiting

, doesn"t it?
Apr.03,2021

here's the thing.

Let's first take a look at the status of state:

0 UNSENT - open()has not been called yet
1 OPENED - send()has not been called yet
2 HEADERS_RECEIVED - send() has been called, and headers and status are available
3 LOADING Downloading; - responseText holds partial data
4 - The operation is complete

if a Synchronize request is sent,
then the browser hangs at this point (after the send code is executed) until the response of the request body is complete, and then changes the state value, triggering the following code:

xhr.onreadystatechange = function () {
    console.log(xhr.readyState)
}

since the response has been requested to complete at this time, the status is directly 4. In other words, what if you can monitor it?

the thread is blocked. What can you do? `

and if it is asynchronous, the callback function of 2p3 state is executed before a real full response is requested.

in addition, Synchronize is not recommended, let alone to monitor onStateChange in Synchronize.

clipboard.png


clipboard.png

if you are interested in reading the standard, you can take a look at https://xhr.spec.whatwg.org/

.
Menu