Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 to continue executing other code while the async function is running. The async keyword is used to declare an async function, and await is used to pause the execution until a specific asynchronous task is completed.
Methods to Create Asynchronous Functions
Using async/await Keywords
The simplest way to create an asynchronous function is to use the async keyword before the function declaration.
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 to use an asynchronous function to fetch data from a server and display it on an HTML page:
<!DOCTYPE html>
<html>
<head>
<title>Async Function Example</title>
</head>
<body>
<p>Click below button to see the result</p>
<button id="get-data">Get Data</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>
Note: The output of the above code may differ with time as the data is coming from an external API.
Using Promises
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('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => resolve(data))
.catch(error => reject(error));
});
}
In this syntax, the fetchData function returns a new promise that fetches data from the server and either resolves with the data or rejects 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 to use a promise to fetch data from a server:
<html>
<body>
<p>Click below button to see the result</p>
<button id="get-button">Get Data</button>
<div id="data-box"></div>
<script>
// Promise-based 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>
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
The Promise.all method returns a promise that resolves when all of the promises passed as an iterable have resolved, or rejects with the reason of the first promise that rejects.
Syntax
async function fetchMultipleData() {
const responses = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2')
]);
const data = await Promise.all(responses.map(res => res.json()));
console.log(data);
}
In this example, the fetchMultipleData function uses the Promise.all method to fetch multiple data from the server and await to wait for all responses before logging the data to the console.
Example
Here's an example of how to use async/await with Promise.all to fetch multiple data simultaneously:
<html>
<body>
<p>Click below button to see the result</p>
<button id="get-button">Get Multiple Data</button>
<div id="data-box"></div>
<script>
// Asynchronous function to fetch multiple data
async function fetchMultipleData() {
const responses = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2')
]);
const data = await Promise.all(responses.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 fetchMultipleData();
// 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>
Note: The output of the above code may differ with time as the data is coming from an external API.
Comparison
| Method | Syntax Complexity | Error Handling | Use Case |
|---|---|---|---|
| async/await | Simple | try/catch blocks | Modern, preferred approach |
| Promises | Moderate | .catch() method | Legacy code, chaining operations |
| Promise.all | Moderate | Single catch for all | Multiple concurrent operations |
Conclusion
JavaScript provides several ways to create asynchronous functions, including async/await, Promises, and Promise.all. The async/await syntax is the most modern and readable approach for handling asynchronous operations, while Promise.all is ideal for running multiple async operations concurrently.
