While it is true, what "kib" stated:
"your function blockfor300ms doesn't block the thread long enough for
the fetch to receive a response"
sadly this is irrelevant, because even if you did block execution until after you received a response to your fetch call, you would still see the same result...
(see sample code snippet below, you can block execution with an alert box or a long loop of non-async XMLHttpRequest calls, I received the same result)
Unfortunately, fetch does not work as described by all the blogs and resources I've found... which state that
Fetch will add it's promise chain to the micro-tasks queue and run before any callbacks on the next tick of the event loop.
From the sample code below, it appears fetch does not simply add it's resolve handler function to the micro-tasks queue as described by others, because as Lewis stated since it requires network activity it is being handled by the Network Task Source. But, I don't believe this is due to printHello "blocking" the network task, because fetch is being fired prior to printHello in my sample code below, and the network response would occur before the timer completed as well.
As you can see in the example below I have the printHello delayed to be added to the Task Queue long after the fetch response has been received (2000ms), yet if we block the code execution for longer than 2000ms (so that there is still running execution context) then "Hello" will be printed first. Meaning the fetch resolve() handler is NOT being simply added to the Micro-Task Queue where it would have fired along with the other promise handlers.
So, why is it still being logged after the callback if the response is received and theoretically added to the Task Queue prior to the timer task completing (at 2000ms)? Well, my guess is that the timer task source must be receiving priority over that of the network task source. And therefore both are sitting in their task queue, but the timer task queue is firing before the network task queue...
Links to specs:
Timer Task Source - https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-task-source
Networking Task Source - https://html.spec.whatwg.org/multipage/webappapis.html#networking-task-source
function display(data){console.log("Fetch resolved!")}
function printHello(){console.log("Callback Time")}
function blockExecution() {
console.log("Blocking execution...");
alert('Wait at least 2000ms before closing');
}
const futureData = fetch('https://jsonplaceholder.typicode.com/todos/1');
futureData.then(response => response.json()).then(display);
setTimeout(printHello, 2000);
const p = new Promise(
// this is called the "executor"
(resolve, reject) => {
console.log("I'm making a promise...");
resolve("Promise resolved!");
console.log("Promise is made...");
}
);
p.then(
// this is called the success handler
result => console.log(result)
);
blockExecution();
console.log("Execution ended!");