fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
setTimeout(()=>{
console.log("Callback after delay")
},1000)
setTimeout(()=>{
console.log("Callback with no delay")
})
console.log("HI this is test")
It is giving the below output:
HI this is test
Callback with no delay
{userId: 1, id: 1, title: 'delectus aut autem', completed: false}
Callback with delay
As callback in promises goes to microtask queue
then callback in fetch
should be execute first and after that setTimeout code with no delay
and then delay
fetch
, setTimeout
both runs asynchronously.
The difference is that --
There is no guaranteed time when the response will come back from fetch
. The code in then will execute when the response is received (when the Promise is resolved).
However, in case of setTimeout
, you provide the timeout. The internal Web APIs of the browser runs a timer of the given duration (milliseconds). After the timer times out, your code will get executed. In your case you have two setTimeout
- one with 0 ms, another 1000 ms. So, first you'll see "Callback with no delay"
, then after one second "Callback after delay"
.
console.log()
runs like synchronous code. So the moment this line executed you'll see the "HI this is test"
text on console.
You're seeing this order, because the fetch
response came back before 1 second. The placement of fetch
response will vary depending on the speed of the network, and response time from the server.
HI this is test
Callback with no delay
{userId: 1, id: 1, title: 'delectus aut autem', completed: false}
Callback with delay
However, these two messages will always be at the top in the same order:
HI this is test
Callback with no delay
I hope the explanation was clear!