Day 17 Async / Await
async/await Promises ka syntactic sugar hai. Promise chains ki jagah synchronous-looking code likhte hain — cleaner aur easier to read.
async / await Basics
async function se await use kar sakte hain. await Promise resolve hone ka wait karta hai.
// async function
async function loadData() {
// await — yahan ruko jab tak promise resolve na ho
let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
let user = await response.json();
console.log(user.name); // Leanne Graham
}
loadData();
// Ye dono same kaam karte hain:
// Promise way:
fetch(url).then(r => r.json()).then(data => console.log(data));
// async/await way (cleaner):
async function getUser() {
let res = await fetch(url);
let data = await res.json();
console.log(data);
}
Error Handling — try/catch
async/await mein errors try/catch se handle karo.
async function fetchUser(id) {
try {
let res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!res.ok) {
throw new Error(`HTTP Error: ${res.status}`);
}
let user = await res.json();
return user;
} catch (error) {
console.error("Failed to fetch user:", error.message);
return null;
} finally {
console.log("Request complete");
}
}
// Call karo
fetchUser(1).then(user => console.log(user?.name));
🎯 Practice Challenge
JSONPlaceholder API (jsonplaceholder.typicode.com) se 5 users fetch karo. Names aur emails console mein print karo.