Booklet
What is Async/Await in Javscript
What is Async/Await in Javascript?
(Explained in 3 min.)
Now imagine this scenario
1. You need to make an API to get user details.
2. You then need to extract the user ID from the details.
3. 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.
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:
(see image)
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.
(See sample below)
No matter what you return here, it ill 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.
(See sample below)
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, it returns the userDetails
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 can only returna Promise at the end. That means your browser is safe from freezing!
Because this function returns a promis, you'll need to call it the usual way:
(See sample below)
And this is what makes async/await so great and so friendly to both the browser, the user and the developer!