Javascript Async Await with Examples

Developers widely use JavaScript, a high-level, dynamic, and interpreted programming language, for developing web applications and creating interactive effects on the web. Async and Await are two powerful features of Javascript that make it possible to write asynchronous code in a way that is much more readable and manageable. In this article, we will discuss what Async and Await are, how they work, and how to use them in Javascript with examples.

What is Asynchronous Programming?

Asynchronous programming is a way of writing code that allows the program to continue executing other tasks while it is waiting for a response from a function call. In other words, it is a way of writing code that does not block the execution of other parts of the code while waiting for a response. This is important in web development because it allows the application to remain responsive even when it is waiting for a response from a server or performing other time-consuming operations.

What are Async & Await?

In JavaScript, developers use the keywords Async and Await together to simplify and enhance the readability of writing asynchronous code. The Async keyword declares a function as asynchronous, indicating that it will return a Promise that resolves when the function completes. Within an Async function, the Await keyword is used to pause execution, waiting for a Promise to resolve before proceeding to the next line of code.

How do Async & Await work?

Async and Await enable a function to pause and wait for the resolution of a Promise before progressing to the subsequent line of code. When a function is declared with the Async keyword, it returns a Promise that resolves upon its completion. Within the function, the Await keyword is utilized to pause execution, awaiting the resolution of the Promise before proceeding to the following line of code. This makes it possible to write asynchronous code in a way that is much more readable and manageable than traditional asynchronous programming techniques.

How to use Async & Await in Javascript

Using Async and Await in Javascript is relatively straightforward. To utilize Async and Await, one can easily declare a function as asynchronous by employing the Async keyword and then leverage the Await keyword within the function to await the resolution of a Promise.

Here is an example of how to use Async and Await in Javascript:

async function getData() {
  const response = await fetch('https://example.com/data');
  const data = await response.json();
  return data;
}

In this example, the getData function is declared as asynchronous using the async keyword. The fetch function is used to retrieve data from a server, and the await keyword is used to wait for the response from the server before continuing with the next line of code. The response from the server is then converted to a JSON object using the json method, and the data is returned from the function.

Examples of Async & Await in Action

To better understand how Async and Await work, let’s take a look at some examples of how they can be used in Javascript.

1: Loading Data from a Server

In this example, we will use Async and Await to load data from a server and display it on the page.

async function loadData() {
  const response = await fetch('https://example.com/data');
  const data = await response.json();
  
  const container = document.getElementById('data-container');
  container.innerHTML = data;
}
loadData();

In this example, the loadData function is declared as asynchronous using the async keyword. The fetch function is used to retrieve data from a server, and the await keyword is used to wait for the response from the server before continuing with the next line of code. The response from the server is then converted to a JSON object using the json method, and the data is displayed on the page by setting the innerHTML property of a container element.

2: Waiting for Multiple Promises to Resolve

In this example, we will use Async and Await to wait for multiple promises to resolve before continuing with the next line of code.

async function getData() {
  const promises = [
    fetch('https://example.com/data1'),
    fetch('https://example.com/data2'),
    fetch('https://example.com/data3')
  ];
  
  const responses = await Promise.all(promises);
  const data = await Promise.all(responses.map(response => response.json()));
  return data;
}
getData().then(data => console.log(data));

In this example, an array of promises is created using the fetch function, and the Promise.all method is used to wait for all of the promises to resolve before continuing with the next line of code. The map method is then used to convert each response to a JSON object, and the data is returned from the function.

3: Handling Errors with Try and Catch

Async and await also make it easier to handle errors in asynchronous code. In traditional JavaScript, errors in asynchronous code are handled by passing a callback function to the catch method on a promise. With async and await, you can use a try and catch block to handle errors in the same way that you would handle errors in synchronous code.

async function getData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}
getData();

In this example, the try block contains the code that may throw an error. If an error is thrown, it is caught by the catch block and the error message is logged to the console. This makes it easier to handle errors in asynchronous code and ensures that your code remains readable and maintainable.

4: Async and Await with Promise Chaining

Using async and await makes it easier to chain multiple promises together. This means that we can execute a series of async functions in sequence, waiting for each to complete before moving on to the next.

For example, suppose we have two functions getData and processData that both return promises. If we want to execute these functions in sequence, we can write the following code:

async function main() {
  const data = await getData();
  const processedData = await processData(data);
  console.log(processedData);
}
main();

In this code, the main function is declared as async, which means that it returns a promise that is resolved when all the async operations inside it are completed. The first line calls getData and waits for its promise to resolve. Once it does, the resolved value is stored in the data variable.

The next line calls processData and passes data as an argument. This function also returns a promise, which is awaited by the main function. Once this promise is resolved, the resolved value is stored in the processedData variable.

Finally, the processed data is logged to the console. This code demonstrates how we can chain multiple promises together using async and await.

5: Async and Await with forEach and map Loops

In addition to chaining promises, we can also use async and await with forEach and map loops. This allows us to execute a series of async operations in parallel, waiting for all of them to complete before moving on.

For example, suppose we have an array of URLs that we want to fetch, and we want to retrieve the data from each URL in parallel. We can write the code for fetching the data from each URL in a function and use the Promise.all() method to fetch the data from all URLs in parallel. The Promise.all() method takes an array of promises as its input and returns a new promise that resolves when all of the input promises have resolved. Here’s an example:

async function fetchData() {
  const urls = [
    'https://jsonplaceholder.typicode.com/posts/1',
    'https://jsonplaceholder.typicode.com/posts/2',
    'https://jsonplaceholder.typicode.com/posts/3'
  ];
  const promises = urls.map(url => fetch(url));
  const results = await Promise.all(promises);
  console.log(results);
}

In this example, the fetchData function creates an array of promises by mapping over the urls array and calling the fetch function on each URL. Then, the function uses the await keyword to wait for the Promise.all() method to resolve, which happens when all of the promises in the promises array have resolved. Finally, the function logs the resolved values of all the promises to the console.

Conclusion

Async and await are an important part of JavaScript and are essential for handling asynchronous programming in a readable and maintainable way. By using async and await, you can write asynchronous code that looks and behaves like synchronous code and handle errors in a familiar way using try and catch. Whether you’re working on a small project or a large enterprise application, async and await are a must-have tool in your JavaScript toolkit.

2 thoughts on “Javascript Async Await with Examples”

  1. Pingback: JavaScript Promises: A Comprehensive Guide for Web Developers - CodeWithNazam

  2. Pingback: Calling Js Promise Inside Another Promise: A Real-World Example - CodeWithNazam

Leave a Comment

Scroll to Top