You might have seen so many definitions across the internet about async/await and promises. I have written this article with simple examples and I am sure that you will easily understand async/await at end of this article.
Before moving into async/await, I would suggest you go through promises from Promise in JavaScript.
What are Async functions 🤔?
Async functions are the functions that don't stop the execution of the rest of the code written after the async function call. In simple terms, calling async functions does not stop the next line from getting executed.
How to create an async function?
A function can be turned into an async function by putting the "async" keyword before that function. Let us take a simple example to have a better understanding of this concept.
A Simple Example
async function HelloWorldAsync() {
return "Hello World";
}
In this example, I have created an async function named HelloWorldAsync(). This function returns a string "Hello World"
If I write code to call this function, can you guess what would be the output? Well, the output will be something as shown in the below image:
Example of Async function and what makes it different from a normal function
As shown in the above image, the async function returns a Promise that it will return a value once it executes. The promise's value can be accessed using then. But before doing that, for your better understanding of async function I would suggest you add 2 lines of code as shown in the below image:
Doing this will give you 2 alert boxes in the sequence as shown in the below image:
Purpose of Async function
Now, let us make some other changes to this code. As the async function returns a promise, let us call show alert inside then() function as shown below:
Running this code will change the sequence of alerts, at first the string "Hii" will be shown and then it will display the message "Hello World". This happens as the function is async, the next line of code will be executed by the time the async function executes. Thus, whenever we want the rest of the code to be executed, instead of waiting for a function to return a value, we can make the function async.
Why await is used?
In the previous example, the sequence of execution is changed as the function is async. What if we want this to be executed in sequence? We would like this to happen if our next line of code needs value returned from the async code.
This can be achieved using await keyword as shown in the below image:
Example of Await keyword
I hope this article is useful to understand async/await. For any queries, you can write to me at [email protected]. To get notified for the releases, subscribe through email. If you found this article useful, please share it. Thank you 😊.