start learning
Image 1

Async and Await

In JavaScript, ASYNC and AWAIT are features introduced in ECMAScript 2017 (ES8) that make it easier to work with asynchronous code and promises.


  1. Async

    keyword is used to define an asynchronous function. It allows the function to use the await keyword inside it. When a function is marked as async, it automatically returns a promise.
  2. Await

    keyword is used inside an async function to pause the execution of the function until a promise is fulfilled or rejected. It can only be used inside an async function, and it waits for the promise to resolve and returns the resolved value. If the promise is rejected, it throws an error that can be caught using a try-catch block.

Using async and await helps to write asynchronous code in a more synchronous and readable manner. It allows you to write asynchronous code that looks and behaves like synchronous code, which can be easier to understand and maintain.
Here's an example to illustrate the usage of async and await :


async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data'); // Pauses execution until the promise is resolved
    const data = await response.json(); // Pauses execution until the promise is resolved
    console.log(data);
  } catch (error) {
    console.log('Error:', error);
  }
}

fetchData();
 

In the above example, the fetchData function is marked as async. Inside the function, the await keyword is used to wait for the fetch request to complete and then for the response to be parsed as JSON. If any error occurs during the process, it is caught and logged to the console.
Note that the use of await is only valid inside an async function.

Here's an example that demonstrates the usage of async and await in combination with HTML :


<!DOCTYPE html>
<html>
<head>
  <title>Async/Await Example</title>
  <script>
    async function fetchData() {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      return data;
    }

    async function displayData() {
      try {
        const data = await fetchData();
        document.getElementById('output').textContent = data.message;
      } catch (error) {
        console.log('Error:', error);
      }
    }
  </script>
</head>
<body>
  <p>Async/Await Example</p>
  <button onclick="displayData()">Fetch Data</button>
  <div id="output"></div>
</body>
</html>
 

In this example, we have an HTML page with a button and a <div> element. When the button is clicked, it triggers the displayData function.

Please note that in order for the example to work properly, the URL 'https://api.example.com/data' should be replaced with a valid API endpoint that returns JSON data.

another example that demonstrates the usage of async and await in JavaScript :


function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function fetchData() {
  console.log('Fetching data...');
  await delay(2000); // Pauses execution for 2 seconds
  console.log('Data fetched!');
  return 'Some data';
}
async function processData() {
  try {
    console.log('Processing data...');
    const result = await fetchData(); // Pauses execution until fetchData() completes
    console.log('Processed:', result);
  } catch (error) {
    console.log('Error:', error);
  }
}
processData();
 

In this example, we have two async functions: fetchData and processData. The fetchData function simulates an asynchronous operation by using the delay function, which returns a promise that resolves after a specified time interval. Inside fetchData, we log a message, pause the execution for 2 seconds using await delay(2000), and then log another message before returning some data.

The processData function demonstrates how await can be used to wait for the completion of an asynchronous operation. Inside processData, we log a message, and then await fetchData(), which pauses the execution of processData until fetchData completes. Once fetchData completes, the result is logged, and the execution continues.
When you run this code, you will see the following output :


Processing data...
Fetching data...
(Data fetch takes 2 seconds)
Data fetched!
Processed: Some data
 

As you can see, await ensures that the execution waits for the asynchronous operation to complete before moving on to the next line of code. This allows you to write asynchronous code that appears to execute in a synchronous manner, enhancing readability and maintainability.


Resources for Further Learning

Explore the possibilities and create unique effects on your web pages by using the interactive code editor

HTML

Write and customize HTML code

CSS

Add style and design to your web pages with CSS

JavaScript

Enhance interactivity with JavaScript code

Go to Code Editor