परिचय
JavaScript एक single-threaded और asynchronous भाषा है।
मतलब यह एक समय में केवल एक काम करती है, लेकिन कुछ काम (जैसे API कॉल, फाइल पढ़ना, टाइमर वगैरह) को background में asynchronously चलाने की क्षमता रखती है।
Async/Await इन्हीं asynchronous operations को सिंपल और readable तरीके से handle करने का तरीका है।
🔹 Async और Await क्या हैं?
🧩 async
जब आप किसी function के आगे async लिखते हैं, तो वह function हमेशा एक Promise return करता है।
async function getData() {
return "Hello Async";
}
getData().then(data => console.log(data)); // Output: Hello Async
ऊपर के कोड में getData() अपने आप Promise बन जाता है।
यानि अब हम .then() या await का इस्तेमाल कर सकते हैं।
🧩 await
await का मतलब है — “रुको जब तक Promise resolve नहीं हो जाता।”
यह केवल async function के अंदर ही इस्तेमाल किया जा सकता है।
async function fetchData() {
console.log("डेटा लोड हो रहा है...");
let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
let data = await response.json();
console.log("डेटा:", data);
}
fetchData();
🔸 await JavaScript को कहता है कि —
“अभी अगले लाइन पर मत जाओ, पहले इस Promise का result लेकर आओ।”
🔹 Async/Await के फायदे
✅ कोड ज्यादा readable और clean बनता है
✅ Error handling आसान हो जाती है (try...catch से)
✅ Callback hell से छुटकारा मिलता है
🔹 Error Handling with try...catch
Async/Await में error को handle करना बहुत आसान होता है।
async function getUserData() {
try {
let res = await fetch("https://invalid-url.com/api");
let data = await res.json();
console.log(data);
} catch (error) {
console.log("❌ Error:", error.message);
}
}
getUserData();
अगर fetch fail हो जाता है, तो catch ब्लॉक अपने आप चल जाएगा।
🔹 एक Real-Life Example
मान लीजिए आपको तीन काम करने हैं:
User data लाना
User की पोस्ट्स लाना
पोस्ट्स दिखाना
Async/Await से यह काम बहुत सिंपल दिखता है 👇
async function showUserPosts() {
try {
let userRes = await fetch("https://jsonplaceholder.typicode.com/users/1");
let user = await userRes.json();
let postRes = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${user.id}`);
let posts = await postRes.json();
console.log(`👤 यूज़र: ${user.name}`);
console.log("📝 पोस्ट्स:", posts);
} catch (err) {
console.log("❌ Error:", err);
}
}
showUserPosts();
Note:-
Async/Await ने JavaScript में asynchronous programming को बहुत आसान और readable बना दिया है।
अब callback hell और .then() चेन से बचकर हम आसानी से clean और maintainable कोड लिख सकते हैं।
💡 Quick Summary
Concept काम Example
async Function को Promise-returning बनाता है async function fn() {}
await Promise के resolve होने का इंतज़ार करता है let data = await promise;
try...catch Error handling के लिए try { ... } catch(e) { ... }