Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
Today we're going to build and run an ice cream shop and learn asynchronous JavaScript at the same time. Along the way, you'll learn how to use:
Callbacks
Promises
Async / Await
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb1j935dg72g9u8zvh2oi.png&width=768&dpr=4&quality=100&sign=4c10c114&sv=1)
Here's what we'll cover in this article:
What is Asynchronous JavaScript?
Synchronous vs Asynchronous JavaScript
How Callbacks Work in JavaScript
How Promises Work in JavaScript
How Async / Await Works in JavaScript
So let's dive in!
You can watch this tutorial on YouTube as well if you like:
What is Asynchronous JavaScript?
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7yd96tgxvuowqmfgcx6b.png&width=768&dpr=4&quality=100&sign=7c96ab0&sv=1)
If you want to build projects efficiently, then this concept is for you.
The theory of async JavaScript helps you break down big complex projects into smaller tasks.
Then you can use any of these three techniques – callbacks, promises or Async/await – to run those small tasks in a way that you get the best results.
Let's dive in!🎖️
Synchronous vs Asynchronous JavaScript
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Farzbf1rc3pi4yi6u8wup.png&width=768&dpr=4&quality=100&sign=a80d4ccd&sv=1)
What is a Synchronous System?
In a synchronous system, tasks are completed one after another.
Think of this as if you have just one hand to accomplish 10 tasks. So, you have to complete one task at a time.
Take a look at the GIF 👇 – one thing is happening at a time here:
![Synchronous System](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FICIS16DkE9qB9HVxtq%2Fgiphy.gif&width=768&dpr=4&quality=100&sign=26b7e297&sv=1)
You'll see that until the first image is loaded completely, the second image doesn't start loading.
Well, JavaScript is by default Synchronous [single threaded]. Think about it like this – one thread means one hand with which to do stuff.
What is an Asynchronous System?
In this system, tasks are completed independently.
Here, imagine that for 10 tasks, you have 10 hands. So, each hand can do each task independently and at the same time.
Take a look at the GIF 👇 – you can see that each image loads at the same time.
![Asynchronous System](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FMMDnmJnE7uhX6KtcKc%2Fgiphy.gif&width=768&dpr=4&quality=100&sign=828a6044&sv=1)
Again, all the images are loading at their own pace. None of them is waiting for any of the others.
To Summarize Synchronous vs Asynchronous JS:
When three images are on a marathon, in a:
Synchronous system, three images are in the same lane. One can't overtake the other. The race is finished one by one. If image number 2 stops, the following image stops.
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw1r9y4ghhq0t8wjb1u9h.png&width=768&dpr=4&quality=100&sign=58ce5893&sv=1)
Asynchronous system, the three images are in different lanes. They'll finish the race on their own pace. Nobody stops for anybody:
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fehknx5shc4orh32s0ktk.png&width=768&dpr=4&quality=100&sign=edeabc59&sv=1)
Synchronous and Asynchronous Code Examples
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpzbnpcza9rbj8xgiby95.png&width=768&dpr=4&quality=100&sign=1697356b&sv=1)
Before starting our project, let's look at some examples and clear up any doubts.
Synchronous Code Example
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5m6p1qy522lj3auvl5ty.png&width=768&dpr=4&quality=100&sign=e13156d6&sv=1)
To test a synchronous system, write this code in JavaScript:
Here's the result in the console: 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F54izy7zyo52j2z6netls.png&width=768&dpr=4&quality=100&sign=74ad8850&sv=1)
Asynchronous code example
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy5d0o8unbe8c67qeqz0w.png&width=768&dpr=4&quality=100&sign=987467aa&sv=1)
Let's say it takes two seconds to eat some ice cream. Now, let's test out an asynchronous system. Write the below code in JavaScript.
Note: Don't worry, we'll discuss the setTimeout()
function later in this article.
And here's the result in the console: 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo44c2t0r7bknkadoumgx.png&width=768&dpr=4&quality=100&sign=d9af1ef3&sv=1)
Now that you know the difference between synchronous and async operations, let's build our ice cream shop.
How to Setup our Project
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2mzbtcnm67v2iys7cix7.png&width=768&dpr=4&quality=100&sign=78fd5944&sv=1)
For this project you can just open Codepen.io and start coding. Or, you can do it in VS code or the editor of your choice.
Open the JavaScript section, and then open your developer console. We'll write our code and see the results in the console.
What are Callbacks in JavaScript?
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs5iloofqsv3lcdl4flsi.png&width=768&dpr=4&quality=100&sign=626507f6&sv=1)
When you nest a function inside another function as an argument, that's called a callback.
Here's an illustration of a callback:
![uz3pl56lmoc2pq7wzi2s](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuz3pl56lmoc2pq7wzi2s.png&width=768&dpr=4&quality=100&sign=eaafd888&sv=1)
Don't worry, we'll see some examples of callbacks in a minute.
Why do we use callbacks?
When doing a complex task, we break that task down into smaller steps. To help us establish a relationship between these steps according to time (optional) and order, we use callbacks.
Take a look at this example:👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo05q7ortgctx2oeyntfn.png&width=768&dpr=4&quality=100&sign=818c295d&sv=1)
These are the small steps you need to take to make ice cream. Also note that in this example, the order of the steps and timing are crucial. You can't just chop the fruit and serve ice cream.
At the same time, if a previous step is not completed, we can't move on to the next step.
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2v1rn50smjul9arkneza.png&width=768&dpr=4&quality=100&sign=c4e61151&sv=1)
To explain that in more detail, let's start our ice cream shop business.
But Wait...
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcq8exwor5aiciu2j6jwu.png&width=768&dpr=4&quality=100&sign=2343286c&sv=1)
The shop will have two parts:
The storeroom will have all the ingredients [Our Backend]
We'll produce ice cream in our kitchen [The frontend]
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi69bws707m5rvsj34i9o.png&width=768&dpr=4&quality=100&sign=6e8ba196&sv=1)
Let's store our data
Now, we're gonna store our ingredients inside an object. Let's start!
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fihezrht8dgg9xn8lm2k9.png&width=768&dpr=4&quality=100&sign=4a64c8b1&sv=1)
You can store the ingredients inside objects like this: 👇
Our other ingredients are here: 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6dcwr770l0ubupv0r2gj.png&width=768&dpr=4&quality=100&sign=4cb71b32&sv=1)
You can store these other ingredients in JavaScript objects like this: 👇
The entire business depends on what a customer orders. Once we have an order, we start production and then we serve ice cream. So, we'll create two functions ->
order
production
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3bnzniiyamo0b9l7e806.png&width=768&dpr=4&quality=100&sign=a049fca5&sv=1)
This is how it all works: 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr8h8ra9wor8cs3dgddpb.png&width=768&dpr=4&quality=100&sign=e7f36157&sv=1)
Let's make our functions. We'll use arrow functions here:
Now, let's establish a relationship between these two functions using a callback, like this: 👇
Let's do a small test
We'll use the console.log()
function to conduct tests to clear up any doubts we might have regarding how we established the relationship between the two functions.
To run the test, we'll call the order
function. And we'll add the second function named production
as its argument.
Here's the result in our console 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu41ugdxxed1q8coz5hol.png&width=768&dpr=4&quality=100&sign=64405b8a&sv=1)
Take a break
So far so good – take a break!
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftnr74waq6noc0djln3qx.png&width=768&dpr=4&quality=100&sign=74581445&sv=1)
Clear out the console.log
Keep this code and remove everything [don't delete our stocks variable]. On our first function, pass another argument so that we can receive the order [Fruit name]:
Here are our steps, and the time each step will take to execute.
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frphpp2lqjnk7f0tv5g3d.png&width=768&dpr=4&quality=100&sign=1f52cdaf&sv=1)
In this chart, you can see that step 1 is to place the order, which takes 2 seconds. Then step 2 is cut the fruit (2 seconds), step 3 is add water and ice (1 second), step 4 is to start the machine (1 second), step 5 is to select the container (2 seconds), step 6 is to select the toppings (3 seconds) and step 7, the final step, is to serve the ice cream which takes 2 seconds.
To establish the timing, the function setTimeout()
is excellent as it is also uses a callback by taking a function as an argument.
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqwrg1taugyhvjnkx8xpp.png&width=768&dpr=4&quality=100&sign=d4eb50a&sv=1)
Now, let's select our fruit and use this function:
And here's the result in the console: 👇
Note that the result is displayed after 2 seconds.
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fedwji5vauypoezj3bxdk.png&width=768&dpr=4&quality=100&sign=24fd6188&sv=1)
If you're wondering how we picked strawberry from our stock variable, here's the code with the format 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fia38z3x6b96xpq3aid91.png&width=768&dpr=4&quality=100&sign=faa73438&sv=1)
Don't delete anything. Now we'll start writing our production function with the following code.👇 We'll use arrow functions:
And here's the result 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5yskzvg7rezo2sg4lklq.png&width=768&dpr=4&quality=100&sign=45acd53&sv=1)
We'll nest another setTimeout
function in our existing setTimeout
function to chop the fruit. Like this: 👇
And here's the result 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4659l1mua0rv40rwyem7.png&width=768&dpr=4&quality=100&sign=cd16bbd6&sv=1)
If you remember, here are our steps:
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frphpp2lqjnk7f0tv5g3d.png&width=768&dpr=4&quality=100&sign=1f52cdaf&sv=1)
Let's complete our ice cream production by nesting a function inside another function – this is also known as a callback, remember?
And here's the result in the console 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5mq9bg6fqrc8apj7nu7b.png&width=768&dpr=4&quality=100&sign=2725840a&sv=1)
Feeling confused?
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fman5l5pwavp9prio1wc0.png&width=768&dpr=4&quality=100&sign=611d105d&sv=1)
This is called callback hell. It looks something like this (remember that code just above?): 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd5rk7f8d920jzn22smjh.png&width=768&dpr=4&quality=100&sign=6cd7613b&sv=1)
What's the solution to this?
How to Use Promises to Escape Callback Hell
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx3neys1hxsrifgg5qm6x.png&width=768&dpr=4&quality=100&sign=7db9191b&sv=1)
Promises were invented to solve the problem of callback hell and to better handle our tasks.
Take a break
But first, take a break!
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbwfvel7kvm422gqvj0os.png&width=768&dpr=4&quality=100&sign=a57f1f90&sv=1)
This is how a promise looks:
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7qo1zheuin2825osozvc.png&width=768&dpr=4&quality=100&sign=2dff7eb5&sv=1)
Let's dissect promises together.
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgozy5r1nfubzeq5t5t25.png&width=768&dpr=4&quality=100&sign=4b9e976&sv=1)
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fezi9ogz0ergprgkmu68a.png&width=768&dpr=4&quality=100&sign=2481fceb&sv=1)
As the above charts show, a promise has three states:
Pending: This is the initial stage. Nothing happens here. Think of it like this, your customer is taking their time giving you an order. But they haven't ordered anything yet.
Resolved: This means that your customer has received their food and is happy.
Rejected: This means that your customer didn't receive their order and left the restaurant.
Let's adopt promises to our ice cream production case study.
But wait...
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F634b6oyglkyoccsvr8l7.png&width=768&dpr=4&quality=100&sign=9be45df8&sv=1)
We need to understand four more things first ->
Relationship between time and work
Promise chaining
Error handling
The
.finally
handler
Let's start our ice cream shop and understand each of these concepts one by one by taking baby steps.
Relationship between time and work
If you remember, these are our steps and the time each takes to make ice cream"
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frphpp2lqjnk7f0tv5g3d.png&width=768&dpr=4&quality=100&sign=1f52cdaf&sv=1)
For this to happen, let's create a variable in JavaScript: 👇
Now create a function named order
and pass two arguments named time, work
:
Now, we're gonna make a promise to our customer, "We will serve you ice-cream" Like this ->
Our promise has 2 parts:
Resolved [ ice cream delivered ]
Rejected [ customer didn't get ice cream ]
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3wik2xel68yue93yapm6.png&width=768&dpr=4&quality=100&sign=fe24c97e&sv=1)
Let's add the time and work factors 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.
Now, we're gonna use our newly created function to start ice-cream production.
The result 👇 after 2 seconds looks like this:
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ferzjup8wt505j502e73n.png&width=768&dpr=4&quality=100&sign=89a40646&sv=1)
Good job!
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8taajvjy6pfq35hu90nq.png&width=768&dpr=4&quality=100&sign=16312b08&sv=1)
Promise chaining
In this method, we defining what we need to do when the first task is complete using the .then
handler. It looks something like this 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl27ytifkoedl22kc97lh.png&width=768&dpr=4&quality=100&sign=4893c2bd&sv=1)
The .then handler returns a promise when our original promise is resolved.
Here's an Example:
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1qpeewo19qbhzj47goos.png&width=768&dpr=4&quality=100&sign=90704091&sv=1)
Let me make it simpler: it's similar to giving instructions to someone. You tell someone to " First do this, then do that, then this other thing, then.., then.., then..." and so on.
The first task is our original promise.
The rest of the tasks return our promise once one small bit of work is completed
Let's implement this on our project. At the bottom of your code write the following lines. 👇
Note: don't forget to write the return
word inside your .then
handler. Otherwise, it won't work properly. If you're curious, try removing the return once we finish the steps:
And here's the result: 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqhhjaakbi6zshxhi6afy.png&width=768&dpr=4&quality=100&sign=31656ac&sv=1)
Using the same system, let's finish our project:👇
Here's the result: 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy0d0f4ys83ctnevkbgxs.png&width=768&dpr=4&quality=100&sign=5b08f186&sv=1)
Error handling
We need a way to handle errors when something goes wrong. But first, we need to understand the promise cycle:
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjlm7zwonbxszeaccyohv.png&width=768&dpr=4&quality=100&sign=c3f0e51a&sv=1)
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz2ajcu52rxzwq64g81vp.png&width=768&dpr=4&quality=100&sign=bbc28d43&sv=1)
To catch our errors, let's change our variable to false.
Which means our shop is closed. We're not selling ice cream to our customers anymore.
To handle this, we use the .catch
handler. Just like .then
, it also returns a promise, but only when our original promise is rejected.
A small reminder here:
.then
works when a promise is resolved.catch
works when a promise is rejected
Go down to the very bottom and write the following code:👇
Just remember that there should be nothing between your previous .then
handler and the .catch
handler.
Here's the result:👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flot6engklu29y05q8xyr.png&width=768&dpr=4&quality=100&sign=79c3c1b5&sv=1)
A couple things to note about this code:
The 1st message is coming from the
reject()
part of our promiseThe 2nd message is coming from the
.catch
handler
How to use the .finally() handler
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgdq3i0agj4volq46ycue.png&width=768&dpr=4&quality=100&sign=153bb29d&sv=1)
There's something called the finally
handler which works regardless of whether our promise was resolved or rejected.
For example: whether we serve no customers 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 this code: 👇
The result:👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft2j3jf2uofip1d6y2rtt.png&width=768&dpr=4&quality=100&sign=2f720aa1&sv=1)
Everyone, please welcome Async / Await~
How Does Async / Await Work in JavaScript?
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fra7483f90b69pjl2cbae.png&width=768&dpr=4&quality=100&sign=c84ca4d3&sv=1)
This is supposed to be the better way to write promises and it helps us keep our code simple and 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
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4vujyfxz7dg41jhjtcrx.png&width=768&dpr=4&quality=100&sign=43e7dd1f&sv=1)
Let's have a look:👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F17f08ygj1odk28hgl9eq.png&width=768&dpr=4&quality=100&sign=51d09914&sv=1)
Promises vs Async/Await in JavaScript
Before async/await, to make a promise we wrote this:
Now using async/await, we write one like this:
But wait......
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft1pjzw6zl0h21tyyh9u3.png&width=768&dpr=4&quality=100&sign=19264929&sv=1)
You need to understand ->
How to use the
try
andcatch
keywordsHow to use the await keyword
How to use the Try and Catch keywords
We use the try
keyword to run our code while we use catch
to catch our errors. It's the same concept we saw when we looked at promises.
Let's see a comparison. We'll see a small demo of the format, then we'll start coding.
Promises in JS -> resolve or reject
We used resolve and reject in promises like this:
Async / Await in JS -> try, catch
When we're using async/await, we use this format:
Don't panic, we'll discuss the await
keyword next.
Now hopefully you understand the difference between promises and Async / Await.
How to Use JavaScript's Await Keyword
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffry577xha7313ead96xy.png&width=768&dpr=4&quality=100&sign=a3d58c22&sv=1)
The keyword await
makes JavaScript wait until a promise settles and returns its result.
How to use the await keyword in JavaScript
Let's go back to our ice cream shop. We don't know which topping a customer might prefer, chocolate or peanuts. So we need to stop our machine and go and ask our customer what they'd like on their ice cream.
Notice here that only our kitchen is stopped, but our staff outside the kitchen will still do things like:
doing the dishes
cleaning the tables
taking orders, and so on.
An Await Keyword Code Example
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8r5w5aapofalnq882wat.png&width=768&dpr=4&quality=100&sign=23d861bb&sv=1)
Let's create a small promise to ask which topping to use. The process takes three seconds.
Now, let's create our kitchen function with the async keyword first.
Let's add other tasks below the kitchen()
call.
And here's the result:
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy0dr669gewtrrd5fd86p.png&width=768&dpr=4&quality=100&sign=ccd603f3&sv=1)
We are literally going outside our kitchen to ask our customer, "what is your topping choice?" In the mean time, other things still get done.
Once, we get their topping choice, we enter the kitchen and finish the job.
Small note
When using Async/ Await, you can also use the .then
, .catch
, and .finally
handlers as well which are a core part of promises.
Let's open our Ice cream shop again
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvzw8gp721oecwo2b3l6s.png&width=768&dpr=4&quality=100&sign=720dd0e0&sv=1)
We're gonna create two functions ->
kitchen
: to make ice creamtime
: to assign the amount of time each small task will take.
Let's start! First, create the time function:
Now, let's create our kitchen:
Let's give small instructions and test if our kitchen function is working or not:
The result looks like this when the shop is open: 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flptup827qau72e83deuv.png&width=768&dpr=4&quality=100&sign=7472a107&sv=1)
The result looks like this when the shop is closed: 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr8pjz1qlw58ap8pq7crz.png&width=768&dpr=4&quality=100&sign=6d580287&sv=1)
So far so good.
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcnkgk63x51wth2byxzfe.png&width=768&dpr=4&quality=100&sign=cf106359&sv=1)
Let's complete our project.
Here's the list of our tasks again: 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7wthn0jr5vw7vb02e4qg.png&width=768&dpr=4&quality=100&sign=eb24a43b&sv=1)
First, open our shop
Now write the steps inside our kitchen()
function: 👇
And here's the result: 👇
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqs9yccq9209u7m9lquju.png&width=768&dpr=4&quality=100&sign=cd08e189&sv=1)
Conclusion
Congratulations for reading until the end! In this article you've learned:
The difference between synchronous and asynchronous systems
Mechanisms of asynchronous JavaScript using 3 techniques (callbacks, promises, and Async/ Await)
Here's your medal for reading until the end. ❤️
Suggestions and criticisms are highly appreciated ❤️
![Alt Text](https://edrus.gitbook.io/~gitbook/image?url=https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fusxsz1lstuwry3jlly4d.png&width=768&dpr=4&quality=100&sign=48f56fca&sv=1)
YouTube / Joy Shaheb
LinkedIn / JoyShaheb
Twitter / JoyShaheb
Instagram / JoyShaheb
Credits
Last updated