Reputation: 945
The javascript runtime environment has an event loop, callback queue, and microtask queue. The functions in the microtask queue get priority over the functions in the callback queue (for getting pushed into the call stack).
Functions returned from the web API like fetch (which returns a promise) get pushed to the microtask queue while functions returned from web APIs as setTimeout gets pushed to the callback queue. So functions returned by the fetch promise will get executed before the setTimeout.
My doubt is, the console is also a web API, right?? now if we simply want the console to log something then the console web API will return the result which technically should first get stored in the callback queue.
So here we can observe that a simple console log should get lower priority than a fetch (since the returned function from fetch gets stored in the microtask queue while the console is stored in the callback queue.).
So theoretically a function returned from fetch should get executed before a simple console log but in reality, the result is reversed. So what am I missing? Please someone clear my doubt please.
Upvotes: 1
Views: 1078
Reputation: 591
Take a look at this snippet
setTimeout(() => console.log('ASYNC'))
Promise.resolve().then(() => console.log('PROMISE')) // also microtask
queueMicrotask(() => console.log('MICROTASK'))
console.log('SYNC')
Upvotes: 2