In JavaScript, an async function is a special type of function that allows you to write asynchronous code in a more synchronous-like manner. It allows you to use the await
keyword to pause the execution of the function until a promise is resolved or rejected.
The syntax for declaring an async function in JavaScript is as follows:
async function functionName() {
// Function body
}
- The
async
keyword is used to declare that the function is an asynchronous function. This keyword allows you to use theawait
keyword inside the function. functionName
is the name you give to your async function. You can choose any valid identifier as the function name.
JavaScript async function example
Simple example code of an async function that fetches data from an API and handles any errors that may occur:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Request failed with status: ' + response.status);
}
const data = await response.json();
console.log('Data:', data);
} catch (error) {
console.log('Error:', error.message);
}
}
Another example
The below code uses a setTimeout to introduce a delay and resolves with the current time:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getCurrentTime() {
await delay(2000); // Introduce a 2-second delay
const currentTime = new Date();
return currentTime;
}
async function printCurrentTime() {
try {
const time = await getCurrentTime();
console.log('Current time:', time);
} catch (error) {
console.log('Error:', error.message);
}
}
printCurrentTime();
Output:
Comment if you have any doubts or suggestions on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version