DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for An async boring sync exampleπŸ˜†
Shihabudheen US
Shihabudheen US

Posted on • Updated on

An async boring sync exampleπŸ˜†

When learning about JavaScript, one would have definitely come across the terms single-threaded, synchronous and asynchronous. In this article, I am trying to explain what it actually means (or at least how I understood).

The boring example πŸ€–.

Let us start with an example. Suppose, you are running a takeaway restaurant. Your menu includes 🍡(tea), β˜•(coffee),πŸ₯ͺ(sandwich) and πŸ”(burger). Yes, you only serve four items for now 🀣. Currently, you operate via a single counter since you are the only employee. You have to take the order, do the billing, and prepare it, and all by yourself. Pretend you are a born multi-tasker πŸ¦Έβ€β™‚οΈ.

With that said, you can only serve a single customer at any point in time. The time to fulfil an order is as follows:

Item Time πŸ•
coffee 2 minutes
sandwich 15 minutes
burger 15 minutes
tea 2 minutes

Since it is a single queue system even β˜• and 🍡 takers have to wait if they behind have any πŸ” or πŸ₯ͺ buyers in the queue. People are people😬, and no one wants to spend their whole day just waiting in a long queue. Soon you found that you are losing the customers, all because of this long wait time😩.

syncCounter.gif

waiting

Now the question is how can you retain your customers and earn more❓ The answer is super simple, reduce the wait time and server more people πŸ†. Let us see two approaches (there are n other approaches as well).

Let us do it

Approach 1️⃣

We can add new 🀡(assistants) for processing the orders and πŸ‘¨β€πŸ³(cooks) for preparation. Now an assistant/waiter will serve a burger or sandwich order. The ready to serve orders can be still managed by youπŸ‹οΈβ€β™‚οΈ. Each time a πŸ” or πŸ₯ͺ order comes up, you call upon a waiter to get it done. The waiter will take the order, inform the cook and wait until the cook prepares the order. Once it is ready, the order is well packed and handed over to the customer by the waiter. To ensure super fast delivery⚑️ for an order, a cook and a waiter work together from order taking to delivery. So the πŸ₯ͺ and πŸ” customers are no more blocking the β˜• or 🍡 orders.

multiThread.gif

❎ The problem with this approach is, the waiter keeps on doing what they are meant to do, waiting... They are simply waiting πŸ„πŸΎβ€β™€οΈ while the food is being cooked. Until an order is placed, the cook is waitingπŸŒπŸΎβ€β™‚οΈ too. In short, now the waiter and cook waste a lot of time just, waiting.

Approach 2️⃣

Let us try introducing a 🏷(token) system only for the πŸ₯ͺ and πŸ” orders. We take the order at a single counter and assign a 🏷 for each πŸ₯ͺ and πŸ” orders. The customer clears the counter after collecting their token. Once the order is ready πŸ›, the token number is called out πŸ“£ and the πŸ“¦(parcel) is handed over through the main counter. Here too, we rely on extra πŸ‘¨β€πŸ³(cooks) for preparation and a 🀡(single waiter). The called out customers join the queue to collect their order.

singleThread.gif

With this approach, the overall πŸ•°(time) has πŸ“ˆincreased (but still lower than the existing model), but the wait time is somewhat judiciously distributed.

Sync vs Async 🎊

Now let us get into the meatπŸ‘½. The currently existing model of operation, the one before the optimization is kind of synchronous flow. Succeeding customers are awaiting for the previous order to be fulfilled. As the customers are blocked by the guys in front of them, we call it a blocking model.

The new two approaches can be considered as asynchronous or non-blocking (still there is a small wait time). As a separate 🀡-πŸ‘¨β€πŸ³ pair is working on a single order, the first approach is more like a multi-threaded one. The second approach is still kind of single-threaded but still unblocking.

Some JS stuff

As per docs, JS is said to be synchronous and single-threaded. Inherently synchronous operations are blocking as we just saw above. Being said, JS is synchronous have you ever felt it πŸ€”? Has your screen frozen when scrolling through your Facebook posts? Next time while googling, try to type and search at the same time(nearly instantaneous). I was able to search for videos, while my YouTube was still playing in mini-player mode. We know that JS is doing all of this in our browser and we were never blocked from multi-task. So is JavaScript actually synchronous? Let me know the answers in comments...πŸ‘‡

If you were paying attention, by now you would have the answer...

down

JS has a single thread (in JS engine) which processes all your tasks. The time taking jobs(n/w calls, timing functions) are pushed out and processed by separate engines. Once they re done, they maintain a secondary queue(callback/microtask queue). Once the high priority/synchronous tasks are completed, the items in the secondary queue are pushed to the main queue(call stack), where they are served one by one, by the main thread. In short, we make the fewer priority tasks WAIT ⏰

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await