Async/Await Functions in JavaScript

As of now, you are familiar with setTimeout(), promises, callback funcitons and other new features of ES2021. Now in this blog, you will have a deep understanding of asynchronous functions, how Async/Await works, and how to make working with promises easier. Async/Await is a special syntax in JavaScript which makes promises easier.

1. What are Asynchronous functions?

Asynchronous functions are those which may not execute simultaneously. In this, other functions can execute without waiting for the previous function to complete its execution.

Let’s take an example to understand this in a better way.

There is a competition in which we need to record the time taken by each participant to complete the race. Let’s take 3 participants, and there are two ways in which we can conduct the competition. First, the participants run one by one, and we record the time taken by each participant; this is the scenario of synchronous functions in which one function starts its execution when the previous one has been completed.

Async/Await
Participants Run One by One

While the second approach is, all the participants run simultaneously and complete the race at their own pace, and we record their time. This is the scenario of asynchronous functions in which one function doesn’t wait on another function for its execution.

Async
Participants Run Simultaneously

2. Async/Await

There are two parts to using async/await in your code.

I. Async Keyword

To make a function asynchronous, we put the async keyword before a function declaration. Async keyword tells to return a promise rather than directly returning the value.

Let’s have an example.

function greet() {
  return "Good Morning" };
   console.log(greet());

Output:

"Good Morning"

This is a simple function without an async keyword.

Now, what if we add an async keyword.

let greet = async function greet(){
  return "Good Morning"
};
console.log(greet());

Output:

"Good Morning"

Now, the invoking of the greet function will return a promise.

II. Await Keyword

Using an async keyword becomes advantageous when you combine it with the await keyword. It works inside the async functions within regular JavaScript code. We put await keyword in front of any promise-based functions to pause the line of code until the promise executes completely and gives results.

Let’s have an example.

async function greet() {
  return greeting = await Promise.resolve("Good Morning");
};

greet().then(alert);

3. Promises VS Async/Await

Let’s look at a simple promise example that we have already seen in our promise blog.

function makeRequest(name){
  return new Promise((resolve, reject) => {
    console.log(`Making Request to ${name}`)
    if (name == 'Facebook') {
        resolve('Hi I am Facebook')
    } else {
      reject('Sorry we can only talk to Facebook')
    }
    })
}

function processRequest(response) {
  return new Promise((resolve, reject) => {
    console.log('Processing response')
    resolve(response)
  })
}

makeRequest('Facebook').then(response => {
  console.log('Response Received')
  return processRequest(response)
}).then(processedResponse => {
      console.log(processedResponse)
}).catch(error => {
  console.log(error)
})

Output:

"Making Request to Facebook"
"Response Received"
"Processing response"
"Hi I am Facebook"

Now, let’s rewrite this code in an Async/Await.

function makeRequest(name){
  return new Promise((resolve, reject) => {
    console.log(`Making Request to ${name}`)
    if (name == 'Facebook') {
        resolve('Hi I am Facebook')
    } else {
      reject('Sorry we can only talk to Facebook')
    }
    })
}

function processRequest(response) {
  return new Promise((resolve, reject) => {
    console.log('Processing response')
    resolve(response)
  })
}

async function processWork() {
    const response = await makeRequest('Facebook')
    console.log('Response Received')
    const processedResponse = await processRequest(response)
    console.log(processedResponse)
}
processWork();

Output:

"Making Request to Facebook"
"Response Received"
"Processing response"
"Hi I am Facebook"

As you can see now, the code looks easier and clean like a synchronous code even though it’s an asynchronous code.

Note: Remember to wrap your code inside a function, whether it is an anonymous function, arrow function, or a normal function.

4. Error Handling with Async/Await

In promises, we handle errors using .then and .catch, while in async/await, we handle errors using the try and catch block.

Let’s have one example.

async function processWork() {
  try {
    const response = await makeRequest('google')
    console.log('Response Recieved')
    const processedResponse = await processRequest(response)
    console.log(processedResponse)
  } catch (error){
    console.log(error)
  }
}
processWork();

5. Conclusion

Hopefully, you understood what async/await is and how they make working with promises easier. Also, async/await is built on the top of promises, so we can use them with all the features provided by promises, including a Promise.all() and  Promise.any().

Some links on this page are affiliate links. This means that if you choose to make a purchase, we may earn a small commission at no extra cost to you. For more information, Go here

Leave a Reply

Your email address will not be published. Required fields are marked *