Async and Await in JavaScript


In this tutorial, we will explore more about Asynchronous programming in JavaScript by learning about Async and Await.

Understanding Async and Await

The async/await syntax is a special feature designed to simplify working with promise objects in JavaScript. It offers a cleaner and more intuitive way to write asynchronous code.

What problem does async/await solve?

The main problem with promises is the chaining of then() and catch() methods. When dealing with multiple promises, the code can become cluttered with numerous then method chains. This is where async/await comes in.

Here is an example of promise chaining:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.log(error));

Now let's see how we can write same code using async/await:

async function fetchTodo() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.log(error);
  }
}

You can see how cleaner the code looks when using async/await.


Async Function

To use async/await in JavaScript, we need to declare an async function.

The async keyword is used to declare an async function. Inside this function, we can use the await keyword. The await keyword is used to wait for a promise to resolve or reject.

Note: The await keyword can only be used inside an async function.

Let's see an example of an async function:

let promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("done!"), 2000);
});

// use async keyword to declare an async function
async function runProcess() {
  // for waiting for a promise to resolve or reject, use await keyword
  let result = await promise; // wait until the promise resolves (*)
  
  alert(result); // "done!"
}

runProcess();

Error Handling in async/await

Just like promises, we can use try/catch block to handle errors in async/await.

Let's see an example:

let promise = new Promise((resolve, reject) => {
  setTimeout(() => reject(new Error("Whoops!")), 2000);
});

// use async keyword to declare an async function
async function runProcess() {
  try {
    // for waiting for a promise to resolve or reject, use await keyword
    let result = await promise; // wait until the promise resolves (*)
  } catch (error) {
    alert(error); // Error: Whoops!
  }
}

runProcess();

Async/Await with different Functions

Async/await can be used with different types of functions, like arrow functions, IIFE etc.

Let's see an example:

// using async/await with arrow function
const runProcess = async () => {
  // code
}

// using async/await with IIFE
(async () => {
  // code
})();

Benefits of Async/Await

The async/await feature offers several advantages over traditional callback or promise-based asynchronous programming:


Conclusion

JavaScript's async/await feature provides developers with a concise and intuitive way to handle asynchronous operations.

By using the async keyword and the await keyword, you can write asynchronous code that is easier to read, write, and maintain. With its simplified syntax and improved error handling, async/await has become an indispensable tool in modern JavaScript development.