Asynchronous Model in JS

Natalia Wit
2 min readSep 28, 2020

--

When I first dipped my hands into learning JavaScript I struggled to understand what asynchronous means. Our browsers manage a lot of tasks, for the browser to run efficiently, we use asynchronous execution. In another context, we can understand asynchronous by thinking — “let me do THIS before THIS other thing finishes.”

Understanding Synchronous vs. Asynchronous with a metaphor

Imagine you are cooking for your family. You are making their favorite chicken cutlet with baked potato and coleslaw. You start making the chicken cutlet and after you finish frying it you then start making the baked potato and then the coleslaw. We call that synchronous way of executing your task. Your family would be so dissatisfied that they got their chicken cutlet first and then 20 minutes after eating that they get the baked potato then coleslaw. WELL, YOU GET THE POINT BY NOW… Instead of doing that you can start preparing the chicken cutlet and while it’s frying on the pan you can start preparing the baked potato. While that’s all happening you can make the coleslaw. That way your family is satisfied and gets everything at the same time and your dinner preparation won’t take as long.

Synchronous Code

In JavaScript, the code executes from top to bottom and left to right. If you type in the above code in the console it will output something like this →

1. Step 1, I will run first
2. Looking for available data.
3. Data is currently [{“name”:”Drake”},{“song”:”Chicago Freestyle”}]
4. I am the last step

Asynchronous code will look something like this —

You can use the window.setTimeout(), which takes in two arguments

A function which is in other words a callback function also used as an arrow (=>)

If you run the above code in the console you will get “Hey there!, I am async” after 3 seconds. This is what makes an asynchronous code amazing. It can do something else while another thing is happening in the background.

In the case of the code below, the second line will run first because the first line async function is taking 3 seconds to execute.

Asynchronous Code

Conclusion:

The asynchronous execution model is very important when we are working with more challenging code. For example, when we are fetching something, we want another part of the code to run for the user to stay on the website. Synchronous code does not always make the best user experience. Just like the meal metaphor above.

--

--

No responses yet