JavaScript single-threaded hai, lekin asynchronous operations iski superpower hain! Jab bhi hum API calls, file operations, ya database queries jaise time-consuming tasks karte hain, asynchronous flow control inka hero ban ke aata hai. Aaj dekhenge kaise callbacks, promises, aur async/await se hum in operations ko smooth tarike se handle kar sakte hain.
1. Callbacks: The OG Asynchronous Pattern
Callbacks woh functions hote hain jo dusre functions ke complete hone par chalta hai. Simple example:
function fetchData(callback) {
setTimeout(() => {
callback('Data aa gaya!');
}, 1000);
}
fetchData((result) => {
console.log(result); // 1 sec baad: "Data aa gaya!"
});
Problem? Callback Hell!
Nested callbacks code ko messy bana dete hain:
getUser((user) => {
getPosts(user, (posts) => {
getComments(posts, (comments) => {
// Pyramid of Doom! 😵
});
});
});
2. Promises: Naya Savior
Promises ne solve kiya callback hell ka problem. Ye teen states mein hote hain:
- Pending
- Resolved (
.then()
se handle) - Rejected (
.catch()
se handle)
Example:
const chaiPromise = new Promise((resolve, reject) => {
const chaiBani = true;
chaiBani ? resolve("Chai ready hai!") : reject("Pani khatam!");
});
chaiPromise
.then((message) => console.log(message))
.catch((error) => console.error(error));
Chaining Promises
Multiple async operations easily chain ho jaate hain:
fetchUser()
.then(user => fetchPosts(user.id))
.then(posts => showPosts(posts))
.catch(error => console.log("Error aaya:", error));
3. Async/Await: Modern Magic ✨
Async/await promises ka readable version hai. async
function ke andar await
lagao:
async function userData() {
try {
const user = await fetchUser();
const posts = await fetchPosts(user.id);
console.log("Posts:", posts);
} catch (error) {
console.log("Pata nahi kya gadbad hui:", error);
}
}
Key Advantages:
- Code synchronous jaisa clean dikhta hai
- Error handling
try/catch
ke through easy hai - Debugging aasan hota hai
Best Practices:
- Callbacks: Simple cases mein use karo (e.g., event listeners)
- Promises/Async-Await: Complex flows ke liye perfect
Promise.all()
: Parallel operations ke liye jadoo:
const [users, posts] = await Promise.all([fetchUsers(), fetchPosts()]);
Conclusion:
Asynchronous flow control JavaScript ki backbone hai. Callbacks se shuruat karo, promises mein upgrade karo, aur async/await se boss ban jaao! Yaad rakho:
“Callback hell se bachna hai? Promises ko gale laga lo!”
Practical code karke dekho – apni next API call async/await se likhne ki koshish karo! 😊