Understanding Async Operations

Restaurant Metaphor

A blocking synchronous restaurant is one where the waiter will wait until your food is ready and served before helping another customer.

A non-blocking asynchronous restaurant is one where the waiter comes to your table, takes your order and give it to the kitchen. The waiter then moves on to server 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 blocking synchronous system, you wash the dishes, when you are done, you take the garbage out.

In a non-blocking asynchronous system, you put the dishes in the dish washer 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). This is a technique where two or more processes start at the same time, run in an interleaved fashion through context switching and complete in an overlapping time period by managing access to shared resources e.g. on a single core of CPU. This feature is called "Multithreading"; Java was design 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 other tasks at the same time.

JavaScript is 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. Any async operation is taken out of the call stack and executed by the hosting environment. (This could be done in a concurrent fashion). 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 will push it to the Call Stack, which effectively runs it.

It is beyond the scope of this course to explore this process in details. Here is a demo of our earlier async code that showcases how these pieces work together. The demo is based off a visualization and a great article by Alexander Zlatkov (read the article here).

I also recommend watching Philip Robert's talk at JSConf EU, What the heck is the event loop anyway? on YouTube.