Search code examples
javascriptxmlhttprequestfetch-api

Why is a XHR Request treated as a macro-task while a Fetch request is treated as a micro-task?


So based on 2 StackOverflow answers, what I have understood is:

  1. XHR callback is queued with Macrotasks
  2. Fetch method is queued with Microtasks

So my question is:

  1. Is this true?
  2. If yes, why is it this way? Shouldn't both of them be treated in the same way?

Solution

  • 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.