Async/Await is a modern way to handle asynchronous operations in JavaScript. It allows developers to write asynchronous code that looks and behaves like synchronous code, making it easier to read and maintain.
An async
function is a function that always returns a Promise
. It allows the use of the await
keyword inside it to pause execution until the promise resolves or rejects.
// Example of an Async Function
async function fetchData() {
return "Data fetched successfully!";
}
fetchData().then(result => console.log(result));
Output: Data fetched successfully!
The await
keyword is used inside an async
function to wait for a promise to resolve or reject before moving to the next line of code.
// Example of Async/Await
async function getData() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data loaded!"), 2000);
});
let result = await promise; // Waits for the promise to resolve
console.log(result);
}
getData();
Output (after 2 seconds): Data loaded!
Async/await
supports error handling using the try/catch
block, making it easy to manage errors in asynchronous operations.
// Example with Error Handling
async function fetchData() {
try {
let promise = new Promise((resolve, reject) => {
setTimeout(() => reject("Error loading data"), 2000);
});
let result = await promise; // Waits for the promise to resolve or reject
console.log(result);
} catch (error) {
console.error(error); // Handles the rejection
}
}
fetchData();
Output (after 2 seconds): Error loading data
try/catch
..then()
and .catch()
.
Async/await
is a powerful feature that enhances JavaScript's asynchronous programming capabilities, making it more intuitive and easier to work with complex code.