Search code examples
javascriptevent-loop

What does fetch do with event loop in browser?


I try to understand event loop of javascript, and I am confused with fetch.

What I know

console.log("1")
Promise.resolve(2)
    .then(data => { console.log(data) })
console.log("3")

The above code executes with results: 1, 3, 2. Since in the first event loop, the engine executes log 1, resolve 2, put then block to micro tasks queue, and log 3, then searches the micro tasks queue and executes log data.

What I am confused

console.log("1")

fetch("some-url")
    .then(data => { console.log(data) })

console.log("3")

After the engine executing log 1, what does it do? Does it immediately execute a HTTP request? If so, does it put the then block to micro task queue? I think it maybe not put the then block to micro task queue, since the data it fetched may not get ready when the current queue is empty and engine starts taking the micro task queue. So how the then block enters micro tasks queue? Does the engine makes a callback to kernel telling it to put the then block into micro tasks queue when response is ready?

If the problem differs in browser and node.js, I prefer the browser answer.


Solution

  • The fetch method will indeed start a network request immediately, which will get processed "in parallel", i.e outside of the event loop.
    When the the request response will be received (not its body, typically the headers), the browser will queue a new task which will only be responsible of resolving that Promise, and thus of queuing its microtask.