So based on 2 StackOverflow answers, what I have understood is:
So my question is:
- Is this true?
- If yes, why is it this way? Shouldn't both of them be treated in the same way?
So based on 2 StackOverflow answers, what I have understood is:
So my question is:
Is this true?
Yes.
When XMLHttpRequest
was created there was no microtask queue. Only one - what is now called the macrotask queue.
However, when fetch()
was introduced, promises were already in the standard. The result of fetch()
is a promise and all effects after a promise resolution are done via the microtask queue:
setTimeout(() => console.log("macrotask done"), 0); //logged second
Promise.resolve().then(() => console.log("microtask done")); //logged first
Hence resolving the promise from fetch()
will also add the subsequent handlers to the microtask queue. Again, it is the one used for the handlers all promises.
If yes, why is it this way? Shouldn't both of them be treated in the same way?
There is no requirement for the two to work the same. Nor would the resolution of these make much of a practical difference in day-to-day code.
Do note that the two are not really the same, either - fetch
will resolve as soon as a result is returned before the body of the result is read. Hence why calling .json()
or .text()
is needed, see Why does .json() return a promise? - calling those methods that will actually process the body. XHR does not have this intermediate step required, its body is processed once it assumes ready state 4 (done).
Is this true?
No. Re-read the answer your linked:
When the the request response will be received […], the browser will queue a new task which will only be responsible of resolving that Promise, […]
I've emphasised the macrotask for you.
Shouldn't both of them be treated in the same way?
No, why would they? One is a promise API, the other is not. Notice that if you wrap XMLHttpRequest
in a promise, you get exactly the same behaviour: the load
/readystatechange
event (a macro task) resolves a promise, scheduling any promise handler (a micro task).
But ultimately you should ask yourself: does it even matter? You normally shouldn't need to concern yourself with such timing details.