Today I Learned - Rocky Kev

TIL Microtask Queue vs the Call Stack Queue

POSTED ON:

TAGS:

This is probably the best graphic I can find to explain this topic.

First, it's the Call Stack.

Things get added to the Call Stack to get executed.
When everything is done from the Call Stack, the Event Loop finds some new tasks to go after.

We used to just call it 'The Event Queue'.
But with the introduction of promises and async, we needed something that takes a bit more priority.

So now, we have the Microtask Queue, and the Macrotask Queue.

1. Microtask Queue

Anything resolved with promises.

The Event Loop will check this place FIRST.

When a Promise resolves and calls its then(), catch() or finally(), method, the function within the method gets added to the microtask queue! This means that the function within the then(), catch() or finally() method isn’t executed immediately. It's added in the microtask queue for processing!

If you make a promise that keeps adding new microtasks queues, it can crash the browser.
In Node, you can "starve" the Macrotask Queue by always adding new microtasks. It'll keep executing the microtask queue, because new things keep getting added.

2. Macrotask Queue

Anything with callbacks.

The big example

If you had some Promises, and a setTimeout Callback that both fired at the same time...
Promises will always show up first.

Via
Will Sentance's course, Javascript, the hard parts: https://frontendmasters.com/courses/javascript-hard-parts-v2/

and

Microtasks and (Macro)tasks in Event Loop


Related TILs

Tagged:

TIL not using try/catch block with promises for error catching

You shouldn't use a try/catch block inside the Promise Definition. Your promise is already doing that.

TIL using proxies for reactivity

A Proxy let you detect when someone gets, sets, or updates a property on an object, and run code when they do. But why? This usecase -- when you add/update the object, it also updates localStorage!

TIL the difference between partial application and currying

Partial application transforms a function into another function with smaller set of arguments. Currying creates nesting functions according to the number of the arguments of the function. Each function receives an argument.