Day 12: Asynchronous JavaScript with Async/Await
What is Asynchronous JavaScript?
Asynchronous JavaScript allows you to perform long-running tasks, like fetching data from an API, without blocking the main thread. This makes your web applications more responsive and user-friendly.
Why Use Async/Await?
- Simplified Syntax: Async/await provides a cleaner and more readable way to work with promises compared to chaining
.then()and.catch()methods. - Error Handling: Easier error handling using
try...catchblocks. - Sequential Execution: Allows for writing asynchronous code that looks and behaves like synchronous code.
How to Use Async/Await
- Defining an Async Function
An async function is declared using the async keyword before the function definition:
async function fetchData() {
// Code inside here is asynchronous
}
- Using
await
The await keyword pauses the execution of the async function until the promise is resolved:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
- Handling Errors
With async/await, you can handle errors using a try...catch block:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}