Asynchronous programming allows your code to run tasks in the background (like fetching data from an API) without freezing the entire website.
👉 Understanding this is the key to mastering data fetching and complex frontend logic.
🔹 1. What is a Promise?
A Promise is a placeholder for a value that will be available in the future. Think of it like a buzzer at a restaurant: you don't have your food yet, but you have a "promise" that it's coming.
A Promise has 3 states:
• Pending: Still waiting for the result.
• Resolved (Fulfilled): Task finished successfully! ✅
• Rejected: Something went wrong. ❌
🔹 2. The Old Way:
.then() and .catch()Before 2017, we handled promises by "chaining" functions. While it works, it can get messy (known as "callback hell").
Example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => print(data))
.catch(error => print("Error found!"));
🔹 3. The Modern Way:
async and awaitThis is the industry standard. It makes asynchronous code look and behave like normal, top-to-bottom code.
•
async: Put this before a function to tell JS it contains asynchronous code.•
await: Put this before a promise to tell JS "wait here until the data arrives."Example:
async function getData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
print(data);
}
🔹 4. Handling Errors with
try...catchWhen using
async/await, we use a try...catch block to handle errors gracefully (like a lost internet connection or a 404 error).Example:
async function safeFetch() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
print(data);
} catch (error) {
print("Network error or invalid API!");
}
}
🔹 5. Why is this important?
• User Experience: Your site stays interactive while loading data.
• Performance: You can fetch multiple pieces of data at the same time.
• Clean Code:
async/await is much easier to read and maintain than old-school callbacks.🎯 What you should do
✔️ Understand the 3 states of a Promise
✔️ Master the
async and await keywords✔️ Learn to handle API errors using
try...catch