DEV Community

Cover image for Illustrated JS: JavaScript asynchronous behaviour
Marina Costa
Marina Costa

Posted on • Updated on

Illustrated JS: JavaScript asynchronous behaviour

While learning JavaScript and programming in general, I find it useful to take notes and create some analogies to understand the concepts. Here I will share some of my notes about the asynchronous behaviour of JavaScript and the fact it’s single threaded. Feel free to correct me if I understood something wrong.

JavaScript has only one thread running for each process. I think about it as a kitchen where only one baker is in charge for the process of baking a cake with chocolate icing.

The baker is the CPU and they would have to execute one subprocess at a time: baking the cake and preparing the icing. After that, the same person would also have to cover the cake with the icing.

Drawing of a baker executing all steps for the cake process


Fig.1 - One baker (CPU) doing one subprocess at a time (single thread)

If it was multithreaded we could have only one CPU executing different subprocesses at the same time (baker with more arms).

Drawing of a baker with multiple arms doing different tasks


Fig.2 - One baker (CPU) doing multiple subprocesses at the same time (multithreads)

Or we could have more CPUs (bakers) working in different subprocesses: cake preparation, icing preparation and cake covering.

Drawing of 3 bakers executing 1 step for the cake process each


Fig.3 - Three bakers executing subprocess concurrently

But in that case, the third subprocess (covering the cake) would need resources from the other two. So it would be necessary to add synchronisation to those actions, but let’s not focus on that right now.

Although multithreading maximises the CPU time, it’s a little bit more complex because it's harder to handle the concurrency, and the results are unpredictable.

Drawing of the oven on fire, burnt icing and the third baker without cake or icing


Fig.4 - Unpredictable results in multithreading (absolutely exaggerated)

It's also important to mention that JavaScript is single threaded but it’s not synchronous. It means it doesn't need to completely finish one task before starting another one.

If that was the case, my baker would have to keep waiting for the oven to finish baking the cake, for instance, before being able to start the icing preparation.

Drawing of a baker staring at the oven waiting for it to finish baking the cake


Fig.5 - The baker is waiting for a slow action (baking the cake) to return before starting the icing preparation

In fact, JavaScript has some resources that allows us to make it asynchronous, and in our cake example, the baker is able to start making the icing while they wait for the cake to be baked.

Drawing of a baker starting the icing preparation while the oven bakes the cake


Fig.6 - Starting the icing preparation without waiting for the cake preparation action to be finished

But let’s say our baker finishes the icing and the cake isn’t baked yet. Without the cake, they would not be able to move to the next step, which is covering the cake with the icing.

Drawing of a baker with the icing but no cake


Fig.7 - The icing is finished before the cake, but the baker can't do the next task (covering the cake)

Many operations in JavaScript depend on external responses like interactions with APIs or network communications and we don’t know for sure when we are going to receive the result of those actions.

That's why we need to make sure that those dependent actions won’t be executed until we have access to the responses they need. For that, we can use promises and I'll talk about that on my next article.

Drawing of an oven with a cake baking inside and the subtitle: promise of a cake


Fig.8 - A promise object wrapping an asynchronous action (baking the cake)

Top comments (43)

Collapse
 
graciegregory profile image
Gracie Gregory (she/her)

Hi @marinafroes !! Any chance you would be willing to submit a brief explanation of this awesome analogy via voice recording so we can feature your voice and thoughts on the DevDiscuss podcast soon? Details are in this post 🙂

Collapse
 
marinafroes profile image
Marina Costa

Hi, Gracie. Why not? I will try to record an explanation and submit it. Thank you for contacting me. 😊

Collapse
 
graciegregory profile image
Gracie Gregory (she/her)

Thank you! We are excited to feature you on DevDiscuss!

Collapse
 
hiboabd profile image
Hibo Abdilaahi

I really enjoyed reading this - you have an ability to explain complex concepts really clearly and simply. I also recently published an article on asychronicity and it was useful to double check my understanding with this article. Keep it up! I'm looking forward to the promises article :)

Collapse
 
marinafroes profile image
Marina Costa

Thanks for the feedback and the encouragement. I've just read your article as well, really nice. :D

Collapse
 
ephraimdavid22 profile image
Agbeze_Obinna

Ma'am, i think Javascript is synchronous by 'default! which means "the Baker needs to finish the baking before moving to icing..that is to say;

// this code would run synchronously
// printing in orderly form
console.log('printing one')
console.log('printing two')

We introduce asynchronous operations into the game when working with APIs as you said.. which means the code below would run asynchronously.
lets use asynchronous function setTimeOut() to simulate a delay comparable to the delays when trying to fetch a data via an API

console.log('printing one')

setTimeout(() => {
    console.log('time up')
}, 2000)

console.log('printing two')

When the code above runs, the two console.log() calls would print first, then the setTimeOut(). This is because by passing a callback function into setTimeOut() we are making the request asynchronous. NB: callback functions typical makes our code asynchronous.

Collapse
 
marinafroes profile image
Marina Costa

Hey Agbeze, thank you for your contribution. :D
In the example above, I can start preparing the icing while I bake the cake because I'm using a promise, as I made a brief reference at the end of the article. In the next article, I explain a little more about promise and I'm writing one that talks about the event loop and setTimeout. I think it will be clearer this way.
Anyway, to make it clearer, I made the following edition in the text:

In fact, JavaScript is asynchronous, and in our cake example, the baker is able to start making the icing while they wait for the cake to be baked.

To:

In fact, JavaScript has some resources that allows us to make it asynchronous, and in our cake example, the baker is able to start making the icing while they wait for the cake to be baked.

Collapse
 
mjgs profile image
Mark Smith

Really like the baking analogy and lovely illustrations.

Perhaps this is splitting hairs but it’s the “javascript runtime“ that is single threaded. The way it’s implemented is slightly different in the browser and in NodeJS, but essentially it’s a system of queues.

This article goes into a bit more depth:

blog.logrocket.com/a-deep-dive-int...

Collapse
 
marinafroes profile image
Marina Costa

Hey Mark, thanks for contributing! I'm glad you mentioned this, one of the next posts that I want to write is about JS environments and this article you shared may help me. Thanks ☺️

Collapse
 
robi_a_p profile image
Bagobo • Edited

Wow you amaze me with ability to explain complex concept to simple.

thx u help me

Collapse
 
marinafroes profile image
Marina Costa

Oh, thanks. :D

Collapse
 
robi_a_p profile image
Bagobo

hi marina, i'm new in javascript. do you have any tips for me to improve skills quickly ?

thx

Thread Thread
 
marinafroes profile image
Marina Costa

After some time learning programming, but not being able to retain most things I learned, I realised that I was getting a lot of input and returning very little output.

In other words, I was learning a lot, but I wasn't writing about it or applying everything I learned, so I was forgetting the concepts and performing poorly in job interviews.

So I suggest that you start writing about the things you learn and apply everything building projects. Also, it is important to share everything you do and ask for feedback, the community is great and supportive and you will learn faster that way.

I hope it helps. 😀

Thread Thread
 
robi_a_p profile image
Bagobo

unfortunately I do not believe in myself to publish my work. I learned a lot but always lost during job interviews so that's how I just freelance and keep learning. maybe after reading your tips I will try to publish my work soon.

Hey marina thanks for the advice, very helpful.

❤️ from me 😎

Thread Thread
 
marinafroes profile image
Marina Costa

I face the same issue and I know many other developers feel the same way, it's the imposter syndrome.
Try to keep in mind that the worst thing that can happen when you publish your work is that someone will tell you that you made a mistake, but in that case you just fix it and learn something new. :D
I wish you all the luck. 😊

Collapse
 
derjontte profile image
John Nordqvist • Edited

I would totally love it if You had an illustration of what happens if the oven hasn't returned a promise of a cake - i.e. the chef just spreading the icing on an empty plate and serve it, which is pretty much how I feel in situations like that... 😜

Collapse
 
marinafroes profile image
Marina Costa

Well, the next post is about promises, there is still an opportunity for that to happen.
I promise I'll think about it. 😂 Thanks for contributing.

Collapse
 
ramesh profile image
Ramesh Elaiyavalli

Great post, Marina! Your illustrations are AMAZING. 🙌

Understand the difference between async and defer. Keep your promises! 🤝

Please take it to the next level. Learn web workers and service workers. They sound similar, do very different things.

Read, post & illustrate with these fantastic sketches. Rinse and repeat.

Soon you will have enough material to publish a JS cartoon book. You get rich, maybe; famous, most definitely!! 😬

Best wishes.

Collapse
 
marinafroes profile image
Marina Costa

Hi Ramesh, thanks so much for your support and feedback. This motivates me to keep learning and doing the illustrations.

I will definitely add the topics you suggested to my learning list.

I already have some other articles in mind, I hope to be able to publish them here soon.

Best, Marina

Collapse
 
marinafroes profile image
Marina Costa

Did you notice any error or know how to improve the explanation? Please help me out and share it on the comments! I would love to learn more about it. :)

Collapse
 
kosich profile image
Kostia Palchyk • Edited

Non tech feedback: now I often end my articles with a dedicated paragraph to wrap things up, promise a next article, ask opinions and "thank reader for reading" 🙂

(maybe with some social links) 😉

Collapse
 
leocck profile image
Leonardo Kasperavičius

"Promise a next article" << I see what you did there ;)

Collapse
 
marinafroes profile image
Marina Costa

Nice, I'll do the same. :D

Collapse
 
sagonz profile image
Sara

I loved the illustrations on these, very adorable and they help illustrate the point in my opinion!

Collapse
 
marinafroes profile image
Marina Costa

Thanks Sara. I'm happy to read this. I started following you and I'm looking forward to reading your future posts.
I'm also looking for my first job on the field, so let's support each other. :D

Collapse
 
sagonz profile image
Sara

All the best! I followed you back! Let's do this :)

Collapse
 
pentacular profile image
pentacular

It might be worthwhile mentioning that you can get more javascript processors to allow parallelism via things like WebWorkers.

Collapse
 
marinafroes profile image
Marina Costa

Yes, I'll read about WebWorkers to learn more about it.
Thanks for contributing. :)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
marinafroes profile image
Marina Costa

Wow, a programmer with an illustration background praising both my illustrations and my article? You made my day. Thanks. :D

Collapse
 
kosich profile image
Kostia Palchyk

This is amazing, Marina 🙂

Collapse
 
marinafroes profile image
Marina Costa

Hi Kostia, thanks a lot. :D

Collapse
 
manyorock profile image
Judith Ogar

I love this piece, so easy to understand thank you.

Collapse
 
marinafroes profile image
Marina Costa

Thanks, I'm glad to read that. :D

Collapse
 
robole profile image
Rob OLeary

Fun illustrations, nice job

Collapse
 
marinafroes profile image
Marina Costa

Thanks :D I'm glad you liked it.

Collapse
 
leocck profile image
Leonardo Kasperavičius

Hey, congratz Marina!
Well written and super helpful article :)

Collapse
 
marinafroes profile image
Marina Costa

Hey Leonardo, thanks! :D