DEV Community

Cover image for Learn callbacks, promises, Async/Await by Making Ice Cream 🍧🍨🍦

Learn callbacks, promises, Async/Await by Making Ice Cream 🍧🍨🍦

Joy Shaheb on June 22, 2021

Today we're gonna run an ice cream shop and learn asynchronous JS. Along the way, we'll understand how to use Callbacks Promises Async / Await ...
Collapse
 
rolfst profile image
Rolf Strijdhorst

Why is everyone confusing asynchronisity with parallelism?
What you describe is parallelism. Async means: the call doesn't complete right away. This can be handled using the eventloop (v8 or something simular) or threads (Java et. al). the loading of images is asynchronous because of latency not because of the runtime.
And following one after another is sequentality.
Often these things can be used interchangeably but not in your examples.
You describe parallelism mostly. One of the key enablers is promise.all() which executes in parallel. An ajax (xhr) request is async and the runtime itself waits on the eventloop to finish this is what promise.all does it waits till all calls are resolved and then continues.

This also makes the async/await confusing since you're making the execution look like a synchronous/sequentual execution while it actually is not.
(I know that was the purpose of the developers though, to make it look synchronous)

Collapse
 
slikts profile image
Reinis Ivanovs

As unkind as that may sound, since a lot of work has obviously gone into the article, it should be unpublished or a significant correction added, because it's actively misleading about what an "evented", non-blocking or async i/o concurrency model is.

Collapse
 
raquelsartwork profile image
Raquel Santos | RS-coding

can you give examples of async JS in real world? I still find Difficult to know when I should use it. Thank you

Collapse
 
longthtran profile image
Long Tran • Edited

You are expected to know the definition of async task, also non-blocking IO (becasue you are JS developers :D ). Here is what I found on stackoverflow: "Point of an async Task is to let it execute in background without locking the main thread, such as doing a DownloadFileAsync".

Most of async task I cope with when coding in JS are: calling API, making a query to database/cache, reading/writing a file,... The reason they are called "async" because you call those functions which are not supposed to return the result "immediately". The moment you call the async task function (lets call func A), your CPU (main thread) is free and it could be used to do another task meanwhile the previous async task function A is in "pending" state waiting for the result to comes back. After then, your JS code shall run to the next line without being blocked at the line you call the async function A; this is not what we want, we expect the code runs sequentially from the top to bottom line by line in case the underneath code must use the result of A ;)

When to use Promise -> When your project is using ES5 or older version, or maybe you are dealing with some library are not written in async/await style.
For ex: a time I played with Google Cloud Storage API written with Promise/callback styles, having some listener method onFinish, onError,... You can wrap their code inside a Promise((resolve, reject) => {}), and your async function return that Promise. From now on, you are freely await your async function!
Sr for the long writing, hope it can help

Collapse
 
raquelsartwork profile image
Raquel Santos | RS-coding

thanl you so much for the explanation :) always a help

Collapse
 
thedailycommute profile image
John C

Off-topic, but in response to Jacob's request to Uriel dos Santos Souza and Raquel Santos to write in English, I highly recommend the Deepl translator - deepl.com/translator, and in particular the free (Windows) application.

I am a native English speaker, but also speak (European) Portuguese, and can confirm that the Deepl translator provided a near perfect English translation of Uriel's post (and significantly better than the attempt by Google Translate :-).

Collapse
 
codewaseem profile image
codewaseem • Edited

I highly appreciate the effort you have put to write this article.

But it looks like you have totally misunderstood the concept of synchronous vs asynchronous code.

The analogy you used here doesn't fit and I would say it is exact opposite to describe asynchronous code, which explains why you misunderstood the concept yourself in the first place.

Asynchronous code has nothing to do with dividing the task in smaller pieces.

In very basic terms, synchronous code will say "Please WAIT and be on the line while I finish processing your request.
And asynchronous code will say "Thank for calling, I will process your request soon, you DON'T HAVE TO WAIT HERE. You can continue with other tasks and I will call you back once I finish.

You can use callbacks, promises, or async/await and still be synchronous, like in your ice-cream example. You are waiting at every step to finish before continuing on to the other. This is what synchronous is.

Synchronous code is blocking, makes you wait.
Asynchronous code is non-blocking, allows you to move forward with other things.

Asynchronous code doesn't mean that it runs on multiple threads. JavaScript is single-threaded, no matter if you write synchronous or asynchronous code.

Please correct your understanding and update the article at its earliest. Otherwise you will end up misleading other developers.

Thanks. Again, I highly appreciate your work.

Collapse
 
raquelsartwork profile image
Raquel Santos | RS-coding

thank you :) can you give me other examples that isn't about fetch data from apis?

 
raquelsartwork profile image
Raquel Santos | RS-coding

I am not a beginner :) This is the subject that I always get me confused to apply in real world. If only to fetch data from apis or other cases. thank you for your answer. you have explained well :)

Thread Thread
 
urielsouza29 profile image
Uriel dos Santos Souza

Oi, sei que vocΓͺ fala portuguΓͺs entΓ£o vou responder na minha lΓ­ngua.
PortuguΓͺs brasileiro.

Se for frontend. Quase tudo de assΓ­ncrono sera para acessar APIs.
Como exemplos:
Mandar algo ser salvo! (via react, ajax, axios ou fetch)
Fazer ediçáes! (via react, ajax, axios ou fetch)
Fazer buscas! (via react, ajax, axios ou fetch)
Esperar por alguma coisa(um ID, um calculo que serΓ‘ feito no banco ou direto no front)

Tudo que se comunique com alguma API vai ter que usar o assincronismo
Hoje praticamente qualquer aplicação minima tem api para acessar!

No back:
Basicamente a mesma coisa
Mandar algo ser salvo no banco de dados
Fazer ediçáes e salvar no banco de dados
Fazer buscas direto no banco de dados!
Fazer cΓ‘lculos, um bom exemplo Γ© fazer encriptagem de senha.
Acessar APIs
Qualquer coisa que leve algum tempo no back devemos usar o assincronismo!
Espero ter ajudado

Thread Thread
 
raquelsartwork profile image
Raquel Santos | RS-coding

Obrigada! Deu para entender ali acima com autor do texto mas obrigada na mesma pelo esclarecimento mais uma vez . :)

Thread Thread
 
devzom profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Jacob • Edited

Write in English

Thread Thread
 
raquelsartwork profile image
Raquel Santos | RS-coding

I said "thank you. I did understand what the author of the post said, but thank you anyway for the explanation again."

Thread Thread
 
devzom profile image
Jacob

I didn't mean that... :) That was a respond to the thread, to point that we all should use English in international website, it's easier to follow and understand subject. But Thank You :)

Thread Thread
 
raquelsartwork profile image
Raquel Santos | RS-coding

of course and you are absolutly right. that is why I translated it my part :)

Collapse
 
riorocker97 profile image
ChangNoi

couldn't wrap my head around when i starting learning about this feature a while ago. this is a nice way to educate myself even more. thank you for creating this.

Collapse
 
mendozalz profile image
Lenin Mendoza

Ey! te felicito tremenda explicaciΓ³n que hasta YO como latino te he comprendido de la mejor manera. Te felicito! sigue asi...

Collapse
 
timhuang profile image
Timothy Huang

Interesting introducing, thank you!

Collapse
 
mrcodedev profile image
MrCodeDev

πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘