How to create an Asynchronous function in JavaScript?


A JavaScript asynchronous function is a function that runs independently of the main flow of the program. This allows the program continues executing other code while the async function is running. Async is used to declare an async function, which runs asynchronously, and await is used to pause the execution of the function until a specific asynchronous task is achieved.

Method to create an Asynchronous function

Using async keyword

The simplest way to create an asynchronous function is to use the async keyword before the function declaration. See the below syntax −

Syntax

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

In this example, the fetchData function uses the await keyword to wait for the data to be fetched from the server before logging it to the console.

Example

Here's an example of how you could use an asynchronous function in JavaScript to fetch data from a server and display it on an HTML page −

<!DOCTYPE html>
<html>
   <head>
      <title>async</title>
   </head>
   <body>
      <p>Click below button to see the result</p>
      <button id="get-data">Get</button>
      <div id="data-box"></div>
      <script>
         // Asynchronous function to fetch data
         async function fetchData() {
            const response = await fetch('https://jsonplaceholder.typicode.com/todos/3');
            const data = await response.json();
            return data;
         }
         // Add click event listener to the button
         const button = document.getElementById('get-data');
         button.addEventListener('click', async () => {
            // Call the asynchronous function
            const data = await fetchData();
            // Use the data to update the HTML
            const dataBox = document.getElementById('data-box');
            dataBox.innerHTML = `<p>Id: ${data.id}</p><p>Title: ${data.title}</p>`;
         });
      </script>
   </body>
</html>

In this example, we have an HTML button with the id "get-button" and a div container with the id "data-box", We added an event listener to the button, so when it's clicked, it calls the asynchronous function fetchData which retrieves the data from the server using the fetch API. Once the data is returned, it is used to update the HTML content of the div container with the id "data-box" with the title and completed the retrieved data.

Note − The output of the above code may differ with time as the data is coming from an external API.

Using promise

Another way to create an asynchronous function is to use the Promise object. A promise is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Syntax

function fetchData() {
   return new Promise((resolve, reject) => {
      fetch('yoururl.com')
      .then(response => response.json())
      .then(data => resolve(data))
      .catch(error => reject(error));
   });
}

In syntax, the fetchData function returns a new promise that fetches the data from the server and either resolves with the data or rejects it with an error. The then and catch methods are used to handle the promise's resolution or rejection.

Example

Here's an example of how you could use a promise in JavaScript to fetch data from a server and display it on an HTML page −

<html>
   <body>
      <p>Click below button to see the result</p>
      <button id="get-button">Get</button>
      <div id="data-box"></div>
      <script>
         // Async promise function to fetch data
         function fetchData() {
            return new Promise((resolve, reject) => {
               fetch('https://jsonplaceholder.typicode.com/todos/3')
               .then(response => response.json())
               .then(data => resolve(data))
               .catch(error => reject(error));
            });
         }
         // Add click event listener to the button
         const button = document.getElementById('get-button');
         button.addEventListener('click', () => {
            // Call the promise
            fetchData()
            .then(data => {
               // Use the data to update the HTML
               const dataBox = document.getElementById('data-box');
               dataBox.innerHTML = `<p>Id: ${data.id}</p><p>Status: ${data.completed}</p>`;
            })
            .catch(error => console.log(error));
         });
      </script>
   </body>
</html>

In this example, we have an HTML button with the id "get-button" and a div container with the id "data-box", We added an event listener to the button, so when it's clicked, it calls the function fetchData which retrieves the data from the server using the fetch API and returns a promise. Once the promise is resolved, it is used to update the HTML content of the div container with the id "data-box" with the Id and completed items of the retrieved data. If the promise is rejected, it will log the error in the console.

Note − The output of the above code may differ with time as the data is coming from an external API.

Using async/await with Promise.all

Promise.all method returns a promise that resolves when all of the promises passed as an iterable has resolved, or rejects with the reason of the first passed promise that rejects.

Syntax

async function fetchData() {
   const response = await Promise.all([
      fetch('https://jsonplaceholder.typicode.com/todos/1'),
      fetch('https://jsonplaceholder.typicode.com/todos/2')
   ]);
   const data = await Promise.all(response.map(res => res.json()));
   console.log(data);
}

In this example, fetchData function uses the Promise.all methods to fetch multiple data from the server and await keywords to wait for all the responses before logging the data to the console.

Example

Here's an example of how you could use async/await with Promise.all in JavaScript to fetch multiple data from a server and display it on an HTML page −

<html>
   <body>
      <p>Click below button to see the result</p>
      <button id="get-button">Get</button>
      <div id="data-box"></div>
      <script>
         // Asynchronous function to fetch data
             async function fetchData() {
            const response = await Promise.all([
               fetch('https://jsonplaceholder.typicode.com/todos/1'),
               fetch('https://jsonplaceholder.typicode.com/todos/2')
            ]);
            const data = await Promise.all(response.map(res => res.json()));
            return data;
         }
         // Add click event listener to the button
         const fetchButton = document.getElementById('get-button');
         fetchButton.addEventListener('click', async () => {
            // Call the async function
            const data = await fetchData();
            // Use the data to update the HTML
            const dataBox = document.getElementById('data-box');
            dataBox.innerHTML = `
            <p>Id 1: ${data[0].id}</p>
            <p>Title 1: ${data[0].title}</p>
            <p>Status 1: ${data[0].completed}</p>
            <p>Id 2: ${data[1].id}</p>
            <p>Title 2: ${data[1].title}</p>
            <p>Status 2: ${data[1].completed}</p>
            `;
         });
      </script>
   </body>
</html>

In this example, we have an HTML button with the id "get-button" and a div container with the id "data-box", We added an event listener to the button, so when it's clicked, it calls the asynchronous function fetchData which retrieves multiple data from the server using the fetch API and Promise.all method. Now it uses the await keyword to wait for all the responses before returning the data, then update the HTML content of the div container with the id "data-box" with the id, title, and completed items of the retrieved data.

Note − The output of the above code may differ with time as the data is coming from an external API.

Conclusion

JavaScript provides several ways to create asynchronous functions, including using the async keyword, Promise object, and async/await with Promise.all. Each method has its own benefits and use cases. The async keyword and await keyword are used to perform tasks that take a long time to complete, such as fetching data from a server, etc.

Updated on: 13-Apr-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements