329
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:
async
Function: When you declare a function with theasync
keyword, it automatically returns a promise. This allows you to use theawait
keyword 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;
}
await
Operator: Theawait
keyword can only be used inside anasync
function. 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...catch
blocks to handle errors when usingasync
andawait
. If a promise rejects, thecatch
block 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
async
functions and useawait
to wait for their results. Remember thatawait
can only be used inside anasync
function 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.