📘 Lesson · Lesson 44
async / await
async / await
What async/await Is
// With Promises (.then chains):
function getData() {
return fetch(url)
.then(res => res.json())
.then(data => console.log(data));
}
// With async/await — reads like synchronous code:
async function getData() {
const res = await fetch(url);
const data = await res.json();
console.log(data);
}
async/await is syntax that lets you write Promise-based code as if it were ordinary, line-by-line synchronous code. Under the hood it's still Promises — nothing has changed about how JavaScript works — but the code reads top to bottom, with no callbacks and no .then() chains. Compare the two versions above: they do exactly the same thing, but the second one looks like the code you've been writing since chapter one. This is the modern way to handle asynchronous work.The async Keyword
async function getData() { } // an async function declaration
const getData = async () => { }; // an async arrow function
// An async function ALWAYS returns a Promise:
async function getName() {
return "Aman"; // wrapped into a Promise automatically
}
getName().then(name => console.log(name)); // "Aman"
Putting
async before a function does two things: it lets you use await inside that function, and it makes the function ALWAYS return a Promise — even if you return a plain value. So return "Aman" inside an async function actually returns a Promise that fulfils with "Aman". This is why calling an async function gives you a Promise you can .then() or await. The keyword goes before function, or before the parameters of an arrow function.The await Keyword
async function getData() {
console.log("Starting");
const res = await fetch(url); // ← PAUSES here until the Promise settles
console.log("Got response"); // runs only after the fetch finishes
const data = await res.json(); // pause again
return data;
}
// ✗ await only works INSIDE an async function:
function bad() {
const res = await fetch(url); // SyntaxError!
}
await pauses the async function until the Promise it's waiting on settles, then hands you the resolved VALUE directly — no .then() needed. It's important to understand that this pause only affects the async function itself; the rest of your page keeps running normally, so nothing freezes. The one hard rule: await can only be used inside an async function. Using it anywhere else is a syntax error — a mistake everyone makes at least once.Error Handling with try...catch
async function getData() {
try {
const res = await fetch(url);
if (!res.ok) throw new Error("HTTP error " + res.status);
const data = await res.json();
console.log(data);
} catch (error) {
console.log("Something failed:", error.message);
} finally {
hideLoadingSpinner(); // always runs
}
}
With Promises you used
.catch(); with async/await you use a normal try...catch block — the same error handling you'd use for any synchronous code. Any rejected Promise that you await throws an error, which catch then receives. This is one of async/await's biggest advantages: one familiar mechanism handles both synchronous and asynchronous errors. Note the res.ok check — fetch does NOT reject on 404 or 500 responses, so you must check the status yourself.A Real Example — fetching and displaying data
async function loadStudents() {
const list = document.querySelector("#studentList");
try {
const res = await fetch("https://api.example.com/students");
if (!res.ok) throw new Error("Could not load students");
const students = await res.json(); // parse the JSON body
list.innerHTML = students
.map(s => `${s.name} — ${s.marks} `)
.join("");
} catch (err) {
list.textContent = "Error: " + err.message;
}
}
loadStudents();
This one small function is what modern front-end JavaScript actually looks like — and it uses nearly everything from this course:
async/await, fetch, JSON parsing, try...catch, template literals, map and join, and DOM manipulation. Data arrives from a server as JSON, becomes an array of objects, is transformed into HTML, and appears on the page. Read it slowly; when this makes complete sense to you, you can build real applications. The AJAX tutorial will explore this pattern in depth.Exam Corner
Q: What does the async keyword do? Allows await inside the function and makes it always return a Promise.
Q: What does await do? Pauses the async function until the Promise settles, returning its resolved value.
Q: Where can you use await? Only inside an async function.
Q: How do you handle errors with async/await? With a try...catch block.
Q: Does fetch() reject on a 404 response? No — check
Q: What does await do? Pauses the async function until the Promise settles, returning its resolved value.
Q: Where can you use await? Only inside an async function.
Q: How do you handle errors with async/await? With a try...catch block.
Q: Does fetch() reject on a 404 response? No — check
res.ok or res.status yourself.
async/await क्या है
// Promises ke saath (.then chains):
function getData() {
return fetch(url)
.then(res => res.json())
.then(data => console.log(data));
}
// async/await ke saath — synchronous code jaisa padhta hai:
async function getData() {
const res = await fetch(url);
const data = await res.json();
console.log(data);
}
async/await ऐसा syntax है जो आपको Promise-आधारित code को साधारण, line-दर-line synchronous code जैसा लिखने देता है. अंदर से यह अब भी Promises है — JavaScript कैसे काम करता है इसमें कुछ नहीं बदला — पर code ऊपर से नीचे पढ़ता है, कोई callbacks नहीं और कोई .then() chains नहीं. ऊपर के दोनों versions तुलना कीजिए: वे ठीक वही करते हैं, पर दूसरा उस code जैसा दिखता है जो आप chapter एक से लिख रहे हैं. Asynchronous काम संभालने का यह आधुनिक तरीका है.async Keyword
async function getData() { } // async function declaration
const getData = async () => { }; // async arrow function
// async function HAMESHA Promise lautata hai:
async function getName() {
return "Aman"; // apne aap Promise me lipta
}
getName().then(name => console.log(name)); // "Aman"
Function से पहले
async लगाना दो काम करता है: यह आपको उस function के अंदर await use करने देता है, और function को HAMESHA Promise लौटाने पर मजबूर करता है — भले ही आप सादी value लौटाएं. तो async function के अंदर return "Aman" असल में ऐसा Promise लौटाता है जो "Aman" से fulfil होता है. इसीलिए async function call करने पर आपको Promise मिलता है जिसे आप .then() या await कर सकते हैं. Keyword function से पहले जाता है, या arrow function के parameters से पहले.await Keyword
async function getData() {
console.log("Starting");
const res = await fetch(url); // ← Promise settle hone tak yahan RUKTA
console.log("Got response"); // fetch khatm hone ke baad hi chalta
const data = await res.json(); // phir rukta
return data;
}
// ✗ await sirf async function ke ANDAR chalta hai:
function bad() {
const res = await fetch(url); // SyntaxError!
}
await async function को तब तक रोकता है जब तक जिस Promise का इंतज़ार है वह settle न हो, फिर आपको सीधे resolved VALUE सौंपता है — कोई .then() नहीं चाहिए. समझना ज़रूरी है कि यह ठहराव सिर्फ उस async function को प्रभावित करता है; आपका बाकी page सामान्य चलता रहता है, तो कुछ नहीं जमता. एक सख्त rule: await सिर्फ async function के अंदर use हो सकता है. कहीं और use करना syntax error है — गलती जो हर कोई कम से कम एक बार करता है.try...catch से Error Handling
async function getData() {
try {
const res = await fetch(url);
if (!res.ok) throw new Error("HTTP error " + res.status);
const data = await res.json();
console.log(data);
} catch (error) {
console.log("Something failed:", error.message);
} finally {
hideLoadingSpinner(); // hamesha chalta
}
}
Promises के साथ आपने
.catch() use किया; async/await के साथ आप सामान्य try...catch block use करते हैं — वही error handling जो किसी synchronous code के लिए करते. जिस rejected Promise को आप await करें वह error फेंकता है, जिसे catch पाता है. यह async/await के सबसे बड़े फायदों में से एक है: एक परिचित तंत्र synchronous और asynchronous दोनों errors संभालता है. res.ok जांच ध्यान दीजिए — fetch 404 या 500 responses पर reject NAHI करता, तो आपको खुद status जांचना होगा.असली Example — data लाना और दिखाना
async function loadStudents() {
const list = document.querySelector("#studentList");
try {
const res = await fetch("https://api.example.com/students");
if (!res.ok) throw new Error("Could not load students");
const students = await res.json(); // JSON body parse karo
list.innerHTML = students
.map(s => `${s.name} — ${s.marks} `)
.join("");
} catch (err) {
list.textContent = "Error: " + err.message;
}
}
loadStudents();
यह एक छोटा function वही है जैसा modern front-end JavaScript असल में दिखता है — और यह इस course की लगभग हर चीज़ use करता है:
async/await, fetch, JSON parsing, try...catch, template literals, map और join, तथा DOM manipulation. Data server से JSON के रूप में आता है, objects की array बनता है, HTML में बदलता है, और page पर दिखता है. धीरे-धीरे पढ़िए; जब यह आपको पूरी तरह समझ आ जाए, आप असली applications बना सकते हैं. AJAX tutorial इस pattern को गहराई से देखेगा.Exam Corner
Q: async keyword क्या करता है? Function के अंदर await की अनुमति देता है और उसे हमेशा Promise लौटाने पर मजबूर करता है.
Q: await क्या करता है? Promise settle होने तक async function को रोकता है, उसकी resolved value लौटाते.
Q: await कहां use कर सकते हैं? सिर्फ async function के अंदर.
Q: async/await के साथ errors कैसे संभालते हैं? try...catch block से.
Q: क्या fetch() 404 response पर reject करता है? नहीं — खुद
Q: await क्या करता है? Promise settle होने तक async function को रोकता है, उसकी resolved value लौटाते.
Q: await कहां use कर सकते हैं? सिर्फ async function के अंदर.
Q: async/await के साथ errors कैसे संभालते हैं? try...catch block से.
Q: क्या fetch() 404 response पर reject करता है? नहीं — खुद
res.ok या res.status जांचिए.
💻 Live Code Editor
इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का
console.log देखने के लिए F12 दबाइए.