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
Table of Contents -
- What's Asynchronous JavaScript
- Synchronous Vs Asynchronous JavaScript
- Callbacks
- Promises
- Async / Await
- Conclusion
You can watch this tutorial on YouTube as well if you like
What's Asynchronous JavaScript ?
If you want to efficiently build projects, Then this is for you.
The theory of async javascript helps you to break down complex & big project into smaller tasks.
And then, using any 1 of these 3 techniques (callbacks, promises or Async/await) we are running those small tasks in a way that we get the final result
Let's Dive in !ποΈ
Synchronous VS Asynchronous ->
Synchronous System
In this system, tasks are completed 1 after another.
Think of this like, you have just 1 hand to accomplish 10 tasks. So, you have to complete 1 task at a time.
Take a look at the GIF π
You can notice that, without loading the 1st image completely, the 2nd image doesn't load.
Note :
By default JavaScript is Synchronous [single threaded] Think like this, 1 thread means 1 hand
Asynchronous System
In this system, tasks are completed independently.
Here, Imagine that For 10 tasks, you're given 10 hands. So, each hand can do the task independently.
Take a look at the GIF π
You can notice that, All the images are loading on their own pace. Nobody is waiting for anybody.
To summarize -
When 3 images are on a marathon, in ->
- Synchronous : 3 images are on the same lane. Overtaking the other is not allowed. The race is finished one by one. If image number 3 stops, everyone stops.
- Asynchronous: 3 images are on different Lanes. They'll finish the race on their own pace. Nobody stops for anybody
Examples
Before starting our project, Let's look at examples and clear our doubts.
Synchronous
To test The synchronous system, Write these on JavaScript
console.log(" I ");
console.log(" eat ");
console.log(" Ice Cream ");
The result on console π
Asynchronous
Let's say it takes 2 seconds to eat ice cream,
Now, let's test The Asynchronous system, Write these on JavaScript.
Note : Don't worry, we'll discuss setTimeout() function in this article.
console.log("I");
// This will be shown after 2 seconds
setTimeout(()=>{
console.log("eat");
},2000)
console.log("Ice Cream")
The result on console π
Setup
For This project you can just open Codepen.io and start coding. Or, you can do it on VS code.
Open The JavaScript section
Once done, open your Developer console window. We'll write code and see the results on the console.
What are Callbacks?
Nesting a function inside another function as an argument are called callbacks.
An illustration of callback ->
Note : Don't worry, Examples are coming.
Why do we use callbacks?
When doing a complex task, we break that task down into small steps. To establish relationship between these steps according to time(Optional) & order, we use callbacks.
Take a look at this π
These are the small steps needed to make ice cream. Also note, order of the steps and timing are crucial. You can't just chop the fruit and serve ice cream.
At the same time, if previous step is not completed, we can't move to the next step.
To explain that in more details, let's start our ice cream shop business
But Wait....
We're gonna have 2 sides.
- The store room will have ingredients [Our Backend]
- We'll produce ice cream on our kitchen [The frontend]
Let's store our data
Now, we're gonna store our ingredients inside an object. Let's start !
store ingredients inside objects Like this π
let stocks = {
Fruits : ["strawberry", "grapes", "banana", "apple"]
}
Our other ingredients are here π
Store them in JavaScript Object like this π
let stocks = {
Fruits : ["strawberry", "grapes", "banana", "apple"],
liquid : ["water", "ice"],
holder : ["cone", "cup", "stick"],
toppings : ["chocolate", "peanuts"],
};
The entire business depends on the order of our customers. Then, starts production and then we serve ice cream. So, we'll create 2 functions ->
- order
- production
See this illustration π
Let's make our functions.
Note : We'll use arrow functions
let order = () =>{};
let production = () =>{};
Now, Let's establish relationship between these 2 functions using a callback. see this π
let order = (call_production) =>{
call_production();
};
let production = () =>{};
Let's do a small test
we'll use the console.log() function to conduct tests to clear our doubts regarding how we established the relationship between the 2 functions.
let order = (call_production) =>{
console.log("Order placed. Please call production")
// function π is being called
call_production();
};
let production = () =>{
console.log("Production has started")
};
To run the test, we'll call the order function. And we'll place the 2nd function named production as it's argument.
// name π of our second function
order(production);
The result on our console π
Take a break
So far so good, Take a break !
Clear our console.log
Keep these code and remove everything [don't delete our stocks variable]. On our 1st function, pass another argument so that we can receive the order [Fruit name]
// Function 1
let order = (fruit_name, call_production) =>{
call_production();
};
// Function 2
let production = () =>{};
// Trigger π
order("", production);
Here's Our steps, and time each step will take to execute.
to establish the timing part, The function setTimeout() is excellent as it is also uses a callback by taking a function as an argument.
Now, Let's select our Fruit.
// 1st Function
let order = (fruit_name, call_production) =>{
setTimeout(function(){
console.log(`${stocks.Fruits[fruit_name]} was selected`)
// Order placed. Call production to start
call_production();
},2000)
};
// 2nd Function
let production = () =>{
// blank for now
};
// Trigger π
order(0, production);
The result on our console π
Note: Result displayed after 2 seconds.
If you're wondering how we picked the strawberry from our stock variable. Here's the code with format π
Don't delete anything. start writing on our production function.
Write these π
Note: We'll use arrow functions.
let production = () =>{
setTimeout(()=>{
console.log("production has started")
},0000)
};
The result π
we'll nest another setTimeout function in our existing setTimeout function to chop the fruit. Like this π
let production = () =>{
setTimeout(()=>{
console.log("production has started")
setTimeout(()=>{
console.log("The fruit has been chopped")
},2000)
},0000)
};
The result π
If you remember, this is the list of our steps.
Let's complete our ice cream production by nesting a function inside another [Also known as Callbacks ]
let production = () =>{
setTimeout(()=>{
console.log("production has started")
setTimeout(()=>{
console.log("The fruit has been chopped")
setTimeout(()=>{
console.log(`${stocks.liquid[0]} and ${stocks.liquid[1]} Added`)
setTimeout(()=>{
console.log("start the machine")
setTimeout(()=>{
console.log(`Ice cream placed on ${stocks.holder[1]}`)
setTimeout(()=>{
console.log(`${stocks.toppings[0]} as toppings`)
setTimeout(()=>{
console.log("serve Ice cream")
},2000)
},3000)
},2000)
},1000)
},1000)
},2000)
},0000)
};
Our result on console π
Feeling confused ?
This is called a callback hell. It looks something like this π
What's the solution to this?
Promises
This was invented to solve the callback hell problem and to better handle our tasks.
Take a break
But first, Take a break !
This is how a promise looks like.
Let's Dissect Promises together !
There're 3 states of a promise
- Pending : This is the initial stage. Nothing happens here. Think like this, your customer is taking his time to give an order. But, hasn't ordered anything.
- Resolve : This means that your customer has received his food and is happy.
- Reject : This means that your customer didn't receive his order and left the restaurant.
Let's adopt promises to our ice cream production.
But wait......
We need to understand 4 more things ->
- Relationship between time & work
- Promise chaining
- Error handling
- .finally handler
Let's start our ice cream shop and understand them one by one by taking small baby steps.
Relationship of time & work
If you remember, these are our steps & time each takes to make ice cream.
For this to happen, Let's create a variable in JavaScript π
let is_shop_open = true;
now create a function named [ order ] and pass 2 arguments named [ work, time ]
let order = ( time, work ) =>{
}
Now, we're gonna make a promise to our customer, "We will serve you ice-cream" Like this ->
let order = ( time, work ) =>{
return new Promise( ( resolve, reject )=>{ } )
}
Note : Our promise has 2 parts ->
- Resolve [ ice cream delivered ]
- Reject [ customer didn't get ice cream ]
let order = ( time, work ) => {
return new Promise( ( resolve, reject )=>{
if( is_shop_open ){
resolve( )
}
else{
reject( console.log("Our shop is closed") )
}
})
}
Let's add the time & work factor inside our Promise using a [ setTimeout() ] function inside our [ if statement ]. Follow me π
Note : In real life, you can avoid the time factor as well. This is completely dependent on the nature of your work.
let order = ( time, work ) => {
return new Promise( ( resolve, reject )=>{
if( is_shop_open ){
setTimeout(()=>{
// work is π getting done here
resolve( work() )
// Setting π time here for 1 work
}, time)
}
else{
reject( console.log("Our shop is closed") )
}
})
}
Now, we're gonna use our newly created function to start ice-cream production. Let's start !
// Set π time here
order( 2000, ()=>console.log(`${stocks.Fruits[0]} was selected`))
// pass a βοΈ function here to start working
The result π after 2 seconds
good job !
Promise chaining
In this method, we are defining what to do when 1st task is complete using the [ .then handler ]. It looks something like this π
The [ .then handler ] returns a promise when our original promise was resolved.
Example :
Let me make it more simple, It's similar to giving instruction to someone. You're telling someone to " First do This, Then do this, then this, then...., then...., then...., etc.
- The first task is our [ original ] promise.
- The rest are returning our promise once 1 small work is completed
Let's implement this on our project. At the bottom write these. π
Note : don't forget to write the [ return ] word inside our [ .then handler ] Otherwise, it won't work properly. If you're curious, try removing the [ return ] word once we finish the steps
order(2000,()=>console.log(`${stocks.Fruits[0]} was selected`))
.then(()=>{
return order(0000,()=>console.log('production has started'))
})
The result π
using the same system, let's finish our project π
// step 1
order(2000,()=>console.log(`${stocks.Fruits[0]} was selected`))
// step 2
.then(()=>{
return order(0000,()=>console.log('production has started'))
})
// step 3
.then(()=>{
return order(2000, ()=>console.log("Fruit has been chopped"))
})
// step 4
.then(()=>{
return order(1000, ()=>console.log(`${stocks.liquid[0]} and ${stocks.liquid[1]} added`))
})
// step 5
.then(()=>{
return order(1000, ()=>console.log("start the machine"))
})
// step 6
.then(()=>{
return order(2000, ()=>console.log(`ice cream placed on ${stocks.holder[1]}`))
})
// step 7
.then(()=>{
return order(3000, ()=>console.log(`${stocks.toppings[0]} as toppings`))
})
// Step 8
.then(()=>{
return order(2000, ()=>console.log("Serve Ice Cream"))
})
The result π
Error handling
This is used to handle our errors when something goes unexpected. But first, understand the promise cycle
To catch our error, let's change our variable to false.
let is_shop_open = false;
Which means our shop is closed. We're not selling ice cream to our customers.
To handle this, we use the [ .catch handler] . Just like the [ .then handler ], It also returns a promise, only when our original promise is rejected.
A small reminder here -
- [.then] works when promise is resolved
- [.catch] works when promise is rejected
come at the very bottom and write π
Note : There should be nothing between your previous .then handler and the .catch handler
.catch(()=>{
console.log("Customer left")
})
The result π
Note :
- 1st message is coming from the reject() part of our promise
- 2nd message is coming from .catch handler
.finally() handler
There's something called the finally handler which works regardless whether our promise was resolved or rejected.
For an example : Serve 0 customer or 100 customers, Our shop will close at the end of the day
If you're curious to test this, come at very bottom and write these π
.finally(()=>{
console.log("end of day")
})
The result π
Everyone ! Please welcome Async / Await !
Async / Await
This is Claimed to be the better way to write promises and helps to keep our code simple & clean.
All you have to do is, write the word [ async ] before any regular function and it becomes a promise.
But first, Take a break
Let's have a look π
Before
To make a promise we wrote
function order(){
return new Promise( (resolve, reject) =>{
// Write code here
} )
}
Now [ using Async / Await ]
In Async / Await method, we make promise like this π
//π the magical keyword
async function order() {
// Write code here
}
But wait......
You need to understand ->
- try, catch usage
- How to use the Await keyword
Try, Catch usage
[ Try ] keyword is used to run our code [ catch ] is used to catch our errors. It's the same concept as of the one we saw on promises.
Let's see a comparison
Note : We'll see a small demo of the format, then we'll start coding
Promises -> Resolve, reject
We used resolve & reject in promises like this ->
function kitchen(){
return new Promise ((resolve, reject)=>{
if(true){
resolve("promise is fulfilled")
}
else{
reject("error caught here")
}
})
}
kitchen() // run the code
.then() // next step
.then() // next step
.catch() // error caught here
.finally() // end of the promise [optional]
Async / Await -> try, catch
Here we work like this format
//π Magical keyword
async function kitchen(){
try{
// Let's create a fake problem
await abc;
}
catch(error){
console.log("abc does not exist", error)
}
finally{
console.log("Runs code anyways")
}
}
kitchen() // run the code
Note : don't panic, we'll discuss about the [await keyword] next
you can notice, the difference between promises, Async / Await
The Await keyword usage
The keyword [ await ] makes JavaScript wait until that promise settles and returns its result.
A practical example
We don't know which topping customer prefers, Chocolate or peanuts?
We need to stop our machine, go and ask our customer, "Sir, which topping would you love ?"
Notice here, only Our kitchen is stopped, but our staff outside the kitchen will still work like
- doing the dishes
- cleaning the tables
- taking orders, etc.
A Code Example
Let's create a small promise, to ask which topping to use. The process takes 3 seconds.
function toppings_choice (){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve( console.log("which topping would you love?") )
},3000)
})
}
now, let's create our kitchen function with the async keyword at first.
async function kitchen(){
console.log("A")
console.log("B")
console.log("C")
await toppings_choice()
console.log("D")
console.log("E")
}
// Trigger the function
kitchen();
Let's add other works below the kitchen() call.
console.log("doing the dishes")
console.log("cleaning the tables")
console.log("taking orders")
The result
We are literally going outside our kitchen to ask our customer, "what is your toppings choice?" In the mean time, other works are done.
Once, we get the toppings choice, we enter the kitchen and finish the job.
Small note
When using Async/ Await, you can also use the [ .then, .catch, .finally ] handlers as well which are a core part of promises.
Let's Open our Ice cream shop Again
We're gonna create 2 functions ->
- kitchen : to make ice cream
- time : assigning amount of time each small task will need to accomplish.
Let's start ! First, create the time function ->
let is_shop_open = true;
function time(ms) {
return new Promise( (resolve, reject) => {
if(is_shop_open){
setTimeout(resolve,ms);
}
else{
reject(console.log("Shop is closed"))
}
});
}
Now, Let's create our kitchen ->
async function kitchen(){
try{
// instruction here
}
catch(error){
// error management here
}
}
// Trigger
kitchen();
Let's give small instructions and test if our kitchen function is working or not
async function kitchen(){
try{
// time taken to perform this 1 task
await time(2000)
console.log(`${stocks.Fruits[0]} was selected`)
}
catch(error){
console.log("Customer left", error)
}
finally{
console.log("Day ended, shop closed")
}
}
// Trigger
kitchen();
The result, When shop is open π
The result when shop is closed π
So far so good !
Let's complete our project.
Here's the list of our task again π
first, open our shop
let is_shop_open = true;
Now write the steps inside our kitchen() function following the steps π
async function kitchen(){
try{
await time(2000)
console.log(`${stocks.Fruits[0]} was selected`)
await time(0000)
console.log("production has started")
await time(2000)
console.log("fruit has been chopped")
await time(1000)
console.log(`${stocks.liquid[0]} and ${stocks.liquid[1]} added`)
await time(1000)
console.log("start the machine")
await time(2000)
console.log(`ice cream placed on ${stocks.holder[1]}`)
await time(3000)
console.log(`${stocks.toppings[0]} as toppings`)
await time(2000)
console.log("Serve Ice Cream")
}
catch(error){
console.log("customer left")
}
}
The result π
Conclusion
Here's Your Medal For reading till the end β€οΈ
Suggestions & Criticisms Are Highly Appreciated β€οΈ
YouTube / Joy Shaheb
LinkedIn / JoyShaheb
Twitter / JoyShaheb
Instagram / JoyShaheb
Top comments (19)
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)
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.
can you give examples of async JS in real world? I still find Difficult to know when I should use it. Thank you
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
thanl you so much for the explanation :) always a help
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 :-).
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.
thank you :) can you give me other examples that isn't about fetch data from apis?
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 :)
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
Obrigada! Deu para entender ali acima com autor do texto mas obrigada na mesma pelo esclarecimento mais uma vez . :)
Write in English
I said "thank you. I did understand what the author of the post said, but thank you anyway for the explanation again."
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 :)
of course and you are absolutly right. that is why I translated it my part :)
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.
Ey! te felicito tremenda explicaciΓ³n que hasta YO como latino te he comprendido de la mejor manera. Te felicito! sigue asi...
Interesting introducing, thank you!
ππππππ
Some comments may only be visible to logged-in visitors. Sign in to view all comments.