How to Implement JavaScript Async/Await

JavaScript is the world’s most widely used programming language, powering over a billion websites. Knowing its ins and outs is super useful for any professional web developer. 

Here, we will talk about one of its key features—JavaScript async/await, which are asynchronous programming constructs. Async and await build on top of promises and generators to express asynchronous actions inline. This article covers the following concepts:

  1. What is synchronous programming?
  2. What is asynchronous programming?
  3. JavaScript async functions
  4. JavaScript async/await demo

What is Synchronous Programming?

Synchronous programming includes the sequential execution of functions and processes. If a particular function needs a resource, execution stops until the currently executing function fetches the resource and finishes its process. 

synchronous

       Synchronous Programming

Although this ensures that the execution is error-free, it’s time-consuming and doesn’t use the system to its full potential. Asynchronous programming solves these issues. 

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

What is Asynchronous Programming?

Asynchronous programming, on the other hand, ensures that the execution does not stop if a function is performing other operations. Instead, the execution continues normally until the function is called back again. To facilitate this, concepts like Callbacks, Promises, and Async/await are used. 

asynchronous

  Asynchronous Programming

JavaScript Async Functions

Async and await are built on promises. The keyword “async” accompanies the function, indicating that it returns a promise. Within this function, the await keyword is applied to the promise being returned. The await keyword ensures that the function waits for the promise to resolve. On the surface, the execution looks synchronous, but it is asynchronous. The function’s execution is blocked at the await keyword’s placement in the coding. Async functions make the code more readable and are easier to handle than promises. 

General syntax: 

async-fun.

Async function - JavaScript Async/Await

Let’s go beyond the basics of async and await, and move on to practicing implementation with a demonstration.

JavaScript Async/Await Demo

First, we’ll look at how a promise typically executes. The use case includes two functions that return promises to verify if you have passed or failed a hypothetical exam and the grade that you have received on that exam. 

let result = function(score){

                return new Promise(function(resolve,reject)

                {

                console.log("Gathering results...");

                if(score>50)

                    resolve("Congratulations! You have Passed" )

                else

                    reject("You have failed")

                })

            }

The function is defined as a value with the name result. It uses a parameter called score that the user provides. The function returns a promise, which resolves or rejects based on the score. 

 let grade = function(response){

                return new Promise(function(resolve,reject)

                {

                console.log("Calculating your grade..");

                resolve("Your grade is A. " + response )

                })

            } 

The next function indicates the score secured. This function uses a parameter called response. The promise gets resolved with a message.

result(80).then(response =>{

                console.log("Results received")

                    return grade(response)

            }).then(finalgrade => {

                console.log(finalgrade)

            }).catch(err => {

                    console.log(err)

            })

The code above calls the functions. The result function is called with a value 80. This is done to show how the code executes when the promise is resolved. The .then method catches the response and indicates that the results are received. To call the grade function, the parameter response is passed as an argument. Since the grade function returns a promise, we can use the .then method over it and catch the result of this promise in finalgrade. 

Finally, to check for errors, we have the .catch method, which executes if the promise is rejected.

The output of the above code is: 

await

Promises - JavaScript Async/Await

If the parameter score value that is being passed to the function result is less than 50, the promise is rejected and the following output is seen: 

failed.

Promises - JavaScript Async/Await

Using async and await helps with code readability, and can help users avoid complicated coding outputs. 

The following is how async and await are implemented: 

async function calculateResults(){

                try {

                    const response = await result(80)

                    console.log("Results received")

                    const finalgrade = await grade(response)

                     console.log(finalgrade)

                    }

                catch(err){

                        console.log(err)

                    }

                }

               

            calculateResults()

We’ve created an async function called calculateResults(). The function result is called with a preceding await keyword. The result of this function is stored in the variable response. Consecutively, the function grade is called with the argument response. The result of this function is stored in the variable finalgrade. This set of code is enclosed within the try block and in case the promise is rejected, the control enters the catch block to display the error message. 

Finally, the async function calculateResults() is called. 

The above code’s output for the score values 80 and 20 are shown below: 

resolution

    Resolution of promise - JavaScript Async/Async

rejection.

  Rejection of Promise - JavaScript Async/Await

Master the complete JavaScript fundamentals, jQuery, Ajax, and more with the Javascript Certification Training Course. Check out the course preview!

Next Steps 

To learn more about JavaScript, gaining certification is highly recommended and could act as a catalyst for your coding career. Simplilearn's JavaScript Certification Training course helps master the JavaScript programming language in an all-inclusive training program that includes complete JavaScript fundamentals, jQuery, Ajax, and more. You will also have the opportunity to apply your skills by building a real-time chat application.

If you have any questions or feedback, let us know in the comments section of our JavaScript async/await article. Our experts will get back to you as soon as possible.

About the Author

Chinmayee DeshpandeChinmayee Deshpande

Chinmayee is a Research Analyst and a passionate writer. Being a technology enthusiast, her thorough knowledge about the subject helps her develop structured content and deliver accordingly.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.