⚙️ Day 17 — Fetch API & Async Operations
Hi Guys Welcome to Day 17 ⚡ Today’s topic connects your JavaScript with the real world — fetching data from external sources and working asynchronously. The Fetch API allows you to make network requests and handle responses without reloading the page.
🌐 1️⃣ What is Fetch API?
The Fetch API provides a simple way to make HTTP requests (GET, POST, etc.). It returns a Promise that resolves to the Response object.
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
🔁 2️⃣ Understanding Promises
A Promise is an object representing a value that may not be available yet. It can be:
- Pending
- Fulfilled
- Rejected
💡 3️⃣ Using async / await
Instead of chaining .then(), you can use async and await to make code cleaner.
async function fetchData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/posts");
let posts = await response.json();
console.log(posts.slice(0, 3));
} catch (err) {
console.log("Error:", err);
}
}
fetchData();
🧮 4️⃣ Real Example — Displaying API Data
You can fetch live JSON data and display it dynamically:
async function showUsers() {
let res = await fetch("https://jsonplaceholder.typicode.com/users");
let users = await res.json();
users.forEach(u => console.log(u.name + " - " + u.email));
}
showUsers();
🧠 5️⃣ Practice Task
- Fetch posts from an API and display titles only.
- Try a
POSTrequest usingfetch()with sample JSON data. - Experiment with
async/awaitandtry...catchfor error handling.
🎯 Summary
You’ve learned how to fetch data asynchronously and handle promises. Tomorrow, you’ll apply all your skills in a small **Mini Project: Interactive To-Do List**!
Comments
Post a Comment