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.

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. 

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

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.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

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

Get access and complete hands-on experience on a plethora of software development skills in our unique Job Guarantee bootcamp. Get job-ready with HackerEarth and HIRIST by enrolling in our comprehensive Full Stack Java Developer Masters program today!

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Next Steps 

To learn more about JavaScript, gaining certification is highly recommended and could act as a catalyst for your coding career. Simplilearn's Java 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
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.