Savvas Stephanides Profile picture
Oct 1, 2020 20 tweets 5 min read Read on X
What is async/await in Javascript? Let's explain

(Thread) 👇🧵

#100DaysOfCode
#CodeNewbies
We've already talked about Promises in a previous thread. Read it if you haven't already. This thread will be a continuation of that thread so please see that first:

So as we mentioned before, Promises are a way of telling Javascript, "go fetch some data but I'm not going to sit and wait because my browser would freeze. When you DO get a response eventually, do THIS with the data".
It would look something like this:

getData("api.example.com/data")
.then((response) => {
console.log(response)
})

Basically:
- request the data
- *when the data is received* print them to the console
Now imagine this scenario:

- You need to make an API call to get user details
- You then need to extract the User ID from the details
- Then you need to make another API call to get user records using the User ID you got from the first API call
You will need to call a Promise within a Promise.
Example:

getData("api.example.com/get-user-detai…")
.then((userDetails) => {
getData("api.example.com/records/" + userDetails.id)
.then((recordsById) => {
console.log(recordsById)
})
})
You can see how this can become messy. What if you need to do 3 API calls? Or 4? Or more? It will become a nightmare to maintain! Take a look at this: A Promise within a promise within a promise
Is there a better way to do this? A cleaner, less messy way that doesn't involve nesting promises within promises within promises?

Yes there is. 👍

Enter: async / await!
async/await is a way to tell the browser, "please sit and wait for data to return before proceeding to the next line (like how other programming languages do it), BUT DO NOT WORRY! I will STILL return a Promise at the end of all this so you won't freeze!"
How do we use this? First we want to make a commitment that this whole thing will return a Promise. This is what "async" does. It declares a function as "asynchronous", basically meaning that it will return a Promise.
This is how it's done:

async function stuffWithData(){

}

No matter what you return here, it will be returned as a Promise.
Now we can tell this function, "whenever you request data, sit and wait for a response before proceeding to the next line. And we do this with the "await" keyword.
Example: A function using async and await keywords to fetch data
What the code above does:

- It prints "Getting user details..." in the console
- Requests some data and *awaits* for them to be returned
- Saves the response in the userDetails variable
- Once this is done, print "All done!" to the console.
But, I hear you ask, didn't we say that sitting and waiting for data to be received will freeze my browser? What's going on here?
In this case, NO! Why? Because we used "async" at the beginning of our function, the function can only return a Promise at the end. That means your browser is safe from freezing! 🙌
With async/await, this is what your code now looks like. Compare this with the previous code. Much less messy right? Code showing an async function calling 3 promises with the a
Because this function returns a Promise, you'll need to call it the usual way:

stuffWithData()
.then((response) => {
console.log(response)
})

And this is what makes async/await so great and so friendly to both the browser, the user and the developer!
Happy browser

Happy user

Happy developer!

Thank you for reading. I hope this made async/await a little clearer!

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Savvas Stephanides

Savvas Stephanides Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @SavvasStephnds

Jan 23, 2023
What are Data Structures? 💿

Let's explain.
When you use a website or an app, a lot of things are going on in the background in order to give its users what they're looking for.

Things are being carried out and the result of these things depend on other things.
One of these things that influence how an app behaves, is the information that it has on hand. For example:

💿 The user's name so the app can give a personalised greeting.
💿 The list of tasks in a to-do list so the app can list them, add things or remove things from it.
Read 12 tweets
Sep 27, 2021
Javascript is the most versatile programming language out there.

You can build anything: interactive web apps, to servers, to mobile and desktop apps.

It does come with its own set of concepts that anyone working with it should know.

Here's 11 of them, explained.

👇🧵
Promises, explained:

savvas.me/explained/prom…
async/await explained:

savvas.me/explained/asyn…
Read 12 tweets
Sep 25, 2021
TOP 5 CHEST PRESS EXERCISES!

Thread 🧵👇 #FitnessWeekend Image
5. MACHINE CHEST PRESS

Equipment: machine

How to do it: bodybuilding.com/exercises/leve… Image
4. CABLE CROSS-OVER

Equipment: cable

How to do it: bodybuilding.com/exercises/cabl… Image
Read 8 tweets
Jun 3, 2021
WHAT IS GRAPHQL?

Let's explain!
This thread is also available in a more readable and accessible format here:

🔗 savvas.me/explained/grap…
You probably heard of GraphQL as a new way to retrieve data from a web service. Possibly as an alternative to REST services. But what is it exactly?
Read 16 tweets
Jun 1, 2021
How I made savvas.me

A thread 🧵👇 Image
1⃣ The stack:

I wanted my website to be as fast and snappy as possible.

Which is why this website is 100% Jamstack. The code, posts, assets are all stored in a repository on Github - github.com/savvasStephani….

...and the website itself is made with Gatsby. Image
2⃣ Hosting

For my website, I wanted for the builds to execute immediately after pushing new changes.

The Markdown blog files, the assets (images, videos), JS files, styling etc are all hosted on Github.

The end result from building the website is hosted and managed on Netlify. Image
Read 9 tweets
Mar 29, 2021
Should I use forEach() or map()?

Both iterate through arrays in Javascript, but how do they differ? Let's see:

Thread 🧵👇

#100DaysOfCode #CodeNewbie #javascript
🚨 This thread is also available in a more accessible version here:

👇

🌐 savvas.netlify.app/explained/fore…
If you're learning Javascript, sooner or later you'll come across the forEach() and map() functions. It is quite often that there is some confusion about what each one does.
Read 15 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us!

:(