604
In this article, you’ll learn about Async and Await in javascript along with error handling.
In JavaScript, the async and await keywords provide a simpler way to work with asynchronous code based on promises. Here’s a brief overview:
asyncFunction: When you declare a function with theasynckeyword, it automatically returns a promise. This allows you to use theawaitkeyword inside the function to wait for promises to resolve. For example:
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
awaitOperator: Theawaitkeyword can only be used inside anasyncfunction. It pauses the execution of the function until the promise is settled (fulfilled or rejected). It then returns the result of the promise. For example:
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}- Error Handling: You can use
try...catchblocks to handle errors when usingasyncandawait. If a promise rejects, thecatchblock will handle the error. For example:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
}
}- Usage: You can call
asyncfunctions and useawaitto wait for their results. Remember thatawaitcan only be used inside anasyncfunction or in a JavaScript module. For example:
async function displayData() {
const data = await fetchData();
console.log(data);
}
displayData();
Using async and await can make your asynchronous code more readable and easier to manage compared to using nested callbacks or promise chains.