Understanding Async Operations
Restaurant Metaphor
A synchronous blocking restaurant is where the waiter will wait until your food is ready and served before helping another customer.
A non-blocking asynchronous restaurant is where the waiter comes to your table, takes your order, and gives it to the kitchen. The waiter then moves on to serve other tables while the chief is preparing your meal. Once your meal is ready, the waiter will get a callback to bring your food to your table.
House chores Metaphor
In a synchronous blocking system, you wash the dishes, and when you are done, you take the garbage out.
In a non-blocking asynchronous system, you put the dishes in the dishwasher and start it. While the dishes are being washed, you clean the kitchen and take the garbage out. Once the dishes are done, the dishwasher will beep to call on you so you can put the clean dishes in the cupboards.
Single vs. Multi Threads
Some programming languages allow concurrent programming (parallel computing). Concurrent programming is a technique where two or more processes start simultaneously, run in an interleaved fashion through context switching, and complete in an overlapping period by managing access to shared resources, e.g., on a single core of CPU. This feature is called "Multithreading"; Java was designed from very early on to provide it. C++ has added it in recent versions.
In our restaurant metaphor,
- a single-threaded program is like having a single chief/cook. All kitchen tasks are done by one person, one after another.
- a multithreaded program is when the chief hires several cooks so while one task is being done (e.g., one meal is being cooked), other cooks can take on additional duties simultaneously.
JavaScript is synchronous and single-threaded.
Event Loop
So how does JavaScript behave asynchronously?
The JavaScript engine relies on the hosting environment, such as the browser, to tell it what to execute next. Therefore, any async operation is taken out of the call stack and managed by the hosting environment. (This could be done concurrently). Once the async job is completed, it will be placed in a callback queue to return to the call stack. This cycle is monitored by a process called the event loop.
The Event Loop monitors the Call Stack and the Callback Queue. If the Call Stack is empty, it will take the first event from the queue and push it to the Call Stack, which effectively runs it.
It is beyond the scope of this course to explore this process in detail. So instead, here is a demo of our earlier async code that showcases how these pieces work together. The demo is based on visualization and a great article by Alexander Zlatkov (see the resources below).
Resources
- Philip Robert's talk at JSConf EU, What the heck is the event loop anyway? on YouTube.
- Alexander Zlatkov's article How JavaScript works: Event loop and the rise of Async programming + 5 ways to better coding with async/await