Single-threaded and Synchronous Programming
Let’s try and visualize this concept, imagine 7:00 in the morning on your way to work you stop by the local McDonald’s and line up in the drive-thru. You decide to make a quick stop to grab a black coffee to day before heading to work. Except that you’re not the only person with this brilliant idea, there’s a whole line up of other cars with their own orders. Some people are ordering coffee, some are ordering breakfast combos, whatever the case may be. You’ve done this a couple hundred times at this point so you know exactly what to expect. This typical morning experience shares the concepts of single threaded and synchronous programming. If we assume that a customer is only considered “served” when they have received their order, this means that only one customer can be served at a time. In a drive-thru lane, only one person can be served at a time (Single-threaded) and they’re always served in the order that they have queued up. You cannot receive your order of black coffee until the people in front of you have received their orders (Synchronous).
Enter Asynchronous Programming
To illustrate this, think back to the McDonald’s drive-thru example. Let’s say that this morning for some reason, there is a large number breakfast sandwich orders. As a result more eggs have to be cracked, wait for the eggs to be cooked, wait for the patties to finish grilling… you get the point. While all this is happening, the line is just getting longer and longer. If McDonald’s continued to operate synchronously, the average wait time for each customer is bottle-necked by the amount of time it takes for breakfast sandwich orders to be fulfilled. To relieve this constraint, McDonald’s can choose to implement an asynchronous action. I’m sure you’ve seen this before, in some McDonald’s there is a designated waiting area for orders that will take some time to complete. This waiting area is McDonald’s answer to the pitfalls of synchronous actions. While the breakfast sandwich order is being prepared, the customer is asked to move to the designated waiting area allowing the customer behind him to be served. Regardless of whether or not the customer at the window has received their order, once the customer’s breakfast sandwich is complete they immediately get served and they’re well on their way. This is a simple example, but it highlights the limitations of synchronous programming and how implementing asynchronous functions can help.
Nothing fancy here, but lets see what happen if we declare and call another function after the setTimeout callback.
Thanks for reading!