Human sense of Vision - Async and Await in JavaScript
Async and Await are modern JavaScript features used to handle asynchronous operations in a simpler and more readable way. They were introduced in ES2017 to make working with promises easier.
What is Asynchronous Programming
In JavaScript, some operations take time to complete, such as fetching data from a server, reading files, or waiting for a timer. Instead of stopping the entire program while waiting, JavaScript runs these tasks asynchronously so other code can continue executing.
Before async and await, developers mainly used callbacks and later promises to manage asynchronous tasks. Async and await provide a cleaner syntax on top of promises.
Async Function
An async function is a function declared with the async keyword. When a function is marked as async, it always returns a promise.
Example:
async function getData() {
return "Hello World";
}
getData().then(function(result) {
console.log(result);
});
In this example, even though the function returns a simple string, JavaScript automatically wraps it inside a promise.
Await Keyword
The await keyword is used inside an async function. It pauses the execution of the function until the promise is resolved or rejected. This makes asynchronous code look similar to synchronous code.
Example:
async function fetchData() {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
}
Here, await waits for the fetch request to complete before moving to the next line.
Handling Errors
Errors in async and await are usually handled using try and catch blocks.
Example:
async function loadData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch(error) {
console.log("Error occurred:", error);
}
}
If the request fails, the catch block will handle the error.
Advantages of Async and Await
Async and await make asynchronous code easier to read and understand.
They reduce complex promise chains and nested callbacks.
They allow better error handling using try and catch blocks.
They make code look more like traditional synchronous programming.
Conclusion
Async and await simplify working with asynchronous operations in JavaScript. They are built on top of promises and help developers write cleaner, more maintainable code when dealing with tasks such as API requests, timers, and file operations.