⚡ Day 8 — Callbacks vs Promises vs Async/Await If you’re learning JavaScript, understanding async patterns is a must 🚀 --- 🧠 1. Callbacks 👉 Functions passed as arguments function getData(cb) { setTimeout(() => cb("Data"), 1000); } ❌ Problem: Callback Hell 😵 👉 Hard to read and maintain when nested --- 🔗 2. Promises 👉 Better way to handle async operations fetchData() .then(res => process(res)) .catch(err => console.log(err)); ✔ Cleaner than callbacks ✔ Supports chaining ✔ Better error handling --- ⚡ 3. Async/Await 👉 Syntactic sugar over Promises async function getData() { try { const res = await fetchData(); console.log(res); } catch (err) { console.log(err); } } ✔ Looks like synchronous code ✔ Easier to read & debug ✔ Most commonly used today --- 🧠 Quick Comparison: Callbacks → Old, messy Promises → Better control Async/Await → Cleanest & modern --- 🔥 One-line takeaway: 👉 “Async/Await is just a cleaner way to write Promises.” --- If you master this, async JavaScript becomes much easier. #JavaScript #AsyncJS #WebDevelopment #Frontend #100DaysOfCode 🚀
Harish Kumar’s Post
More Relevant Posts
-
"Promises vs Async/Await — which one should you use?" 🤔 If you're working with asynchronous JavaScript, this is something you should clearly understand 👇 🔹 Promises - Handle async operations - Use ".then()" and ".catch()" - Can become messy with chaining 💻 Example: fetchData() .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); 🔹 Async/Await - Built on top of Promises - Makes code look synchronous - Easier to read & debug 💻 Example: async function getData() { try { const res = await fetchData(); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } 🔹 Key Difference 👉 Promises → chaining based 👉 Async/Await → cleaner & readable 🚀 Pro Tip: Use Async/Await for better readability, but understand Promises deeply (they’re the foundation). 💬 Which one do you prefer in your projects? #javascript #webdevelopment #mern #coding #developers
To view or add a comment, sign in
-
Day 5 ⚡ Async/Await in JavaScript — The Clean Way to Handle Async Code If you’ve struggled with .then() chains, async/await is your best friend 🚀 --- 🧠 What is async? 👉 Makes a function always return a Promise async function greet(){ return "Hello"; } greet().then(console.log); // Hello --- ⏳ What is await? 👉 Pauses execution until a Promise resolves function delay(){ return new Promise(res => setTimeout(() => res("Done"), 1000)); } async function run(){ const result = await delay(); console.log(result); } --- ⚡ Why use async/await? ✔ Cleaner than .then() chaining ✔ Looks like synchronous code ✔ Easier error handling --- ❌ Sequential vs ⚡ Parallel // ❌ Sequential (slow) const a = await fetchUser(); const b = await fetchPosts(); // ⚡ Parallel (fast) const [a, b] = await Promise.all([ fetchUser(), fetchPosts() ]); --- ⚠️ Error Handling try { const data = await fetchData(); } catch (err) { console.log("Error handled"); } --- 💡 One-line takeaway 👉 async/await = cleaner + readable way to handle Promises #JavaScript #AsyncAwait #WebDevelopment #Frontend #Coding #100DaysOfCode
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁 𝗩𝗶𝘀𝘂𝗮𝗹𝗶𝘇𝗲𝗱 Confused about how async code really flows in JavaScript? Here’s a clean breakdown to make it click 👇 🔹 Promise → Starts in a pending state (⏳) 🔹 resolved → Success path (✅) → handled with .then() 🔹 rejected → Error path (❌) → handled with .catch() That’s the traditional flow — powerful, but can get messy with chaining. Now the modern way 👇 🔹 async/await simplifies everything 🔹 await pauses execution until the Promise resolves 🔹 try {} → handles success 🔹 catch {} → handles errors 💡 Same logic, cleaner syntax, easier to read Instead of chaining: ➡️ .then().catch() You write: ➡️ try { await ... } catch (error) {} Much closer to synchronous code — and way easier to debug. 🚀 Understanding this flow = writing cleaner async code + fewer bugs If you're working with APIs, interviews, or real-world apps… this is essential. 📚 𝗦𝗼𝘂𝗿𝗰𝗲𝘀: • JavaScript Mastery • w3schools.com Follow for more: Enea Zani #async #await #javascript #webdevelopment #frontend #reactjs #coding #developers #programming #100DaysOfCode #learnjavascript #softwareengineer
To view or add a comment, sign in
-
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁 𝗩𝗶𝘀𝘂𝗮𝗹𝗶𝘇𝗲𝗱 Confused about how async code really flows in JavaScript? Here’s a clean breakdown to make it click 👇 🔹 Promise → Starts in a pending state (⏳) 🔹 resolved → Success path (✅) → handled with .then() 🔹 rejected → Error path (❌) → handled with .catch() That’s the traditional flow — powerful, but can get messy with chaining. Now the modern way 👇 🔹 async/await simplifies everything 🔹 await pauses execution until the Promise resolves 🔹 try {} → handles success 🔹 catch {} → handles errors 💡 Same logic, cleaner syntax, easier to read Instead of chaining: ➡️ .then().catch() You write: ➡️ try { await ... } catch (error) {} Much closer to synchronous code — and way easier to debug. 🚀 Understanding this flow = writing cleaner async code + fewer bugs If you're working with APIs, interviews, or real-world apps… this is essential. 📚 𝗦𝗼𝘂𝗿𝗰𝗲𝘀: • JavaScript Mastery • w3schools.com Follow for more: Arun Dubey #async #await #javascript #webdevelopment #frontend #reactjs #coding #developers #programming #100Days #learnjavascript #softwareengineer
To view or add a comment, sign in
-
-
𝐀𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐉𝐒 (2) 🚀 𝑭𝒓𝒐𝒎 𝑪𝒂𝒍𝒍𝒃𝒂𝒄𝒌 𝑯𝒆𝒍𝒍 𝒕𝒐 𝑷𝒓𝒐𝒎𝒊𝒔𝒆𝒔 — 𝑻𝒂𝒌𝒊𝒏𝒈 𝑪𝒐𝒏𝒕𝒓𝒐𝒍 𝒐𝒇 𝑨𝒔𝒚𝒏𝒄 While learning asynchronous JavaScript, I recently explored one of the most powerful concepts — Promises. 👉 𝑻𝒉𝒆 𝑷𝒓𝒐𝒃𝒍𝒆𝒎 𝒘𝒊𝒕𝒉 𝑪𝒂𝒍𝒍𝒃𝒂𝒄𝒌𝒔 We used callbacks to handle dependent async operations like: 🛒 createOrder → proceedToPayment But this led to: ❌ Callback Hell (nested, unreadable code) ❌ Inversion of Control (trusting external code blindly) 💡 Enter Promises — A Better Way 𝘈 𝘗𝘳𝘰𝘮𝘪𝘴𝘦 𝘪𝘴 𝘢𝘯 𝘰𝘣𝘫𝘦𝘤𝘵 𝘵𝘩𝘢𝘵 𝘳𝘦𝘱𝘳𝘦𝘴𝘦𝘯𝘵𝘴 𝘵𝘩𝘦 𝘦𝘷𝘦𝘯𝘵𝘶𝘢𝘭 𝘤𝘰𝘮𝘱𝘭𝘦𝘵𝘪𝘰𝘯 (𝘰𝘳 𝘧𝘢𝘪𝘭𝘶𝘳𝘦) 𝘰𝘧 𝘢𝘯 𝘢𝘴𝘺𝘯𝘤 𝘰𝘱𝘦𝘳𝘢𝘵𝘪𝘰𝘯. Instead of passing control to another function, 👉 we attach our logic to the promise. const promise = createOrder(cart); 𝘱𝘳𝘰𝘮𝘪𝘴𝘦.𝘵𝘩𝘦𝘯(𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯(𝘰𝘳𝘥𝘦𝘳𝘐𝘥) { 𝘳𝘦𝘵𝘶𝘳𝘯 𝘱𝘳𝘰𝘤𝘦𝘦𝘥𝘛𝘰𝘗𝘢𝘺𝘮𝘦𝘯𝘵(𝘰𝘳𝘥𝘦𝘳𝘐𝘥); }); ⭐ Key Insight: There’s a big difference between ➡️ Passing a function (callbacks) ➡️ Attaching a function (promises) With promises, we stay in control. 🔄 𝑷𝒓𝒐𝒎𝒊𝒔𝒆 𝑺𝒕𝒂𝒕𝒆𝒔: Every promise has 3 states: ⏳ Pending ✅ Fulfilled ❌ Rejected And once resolved, a promise is immutable (cannot be changed). 🌍 𝑹𝒆𝒂𝒍 𝑬𝒙𝒂𝒎𝒑𝒍𝒆 (𝑭𝒆𝒕𝒄𝒉 𝑨𝑷𝑰): fetch("https://lnkd.in/dS_8dpyv") .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); 👉 fetch() returns a promise 👉 .then() handles success 👉 .catch() handles errors 🔥 Why Promises are Better ✔️ Avoid callback hell ✔️ Better readability ✔️ More control over execution ✔️ Built-in error handling 💭 𝑭𝒊𝒏𝒂𝒍 𝑻𝒉𝒐𝒖𝒈𝒉𝒕: Promises made async JavaScript predictable and reliable — and paved the way for async/await. #JavaScript #AsyncJS #Promises #FrontendDevelopment #ReactJS #WebDevelopment #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
-
𝑨𝒔𝒚𝒏𝒄𝒉𝒓𝒐𝒏𝒐𝒖𝒔 𝑱𝑺 (1) 🚀 𝑼𝒏𝒅𝒆𝒓𝒔𝒕𝒂𝒏𝒅𝒊𝒏𝒈 𝑪𝒂𝒍𝒍𝒃𝒂𝒄𝒌𝒔 𝒊𝒏 𝑱𝒂𝒗𝒂𝑺𝒄𝒓𝒊𝒑𝒕 (𝑻𝒉𝒆 𝑮𝒐𝒐𝒅 & 𝑻𝒉𝒆 𝑩𝒂𝒅) While diving deeper into asynchronous JavaScript, I explored one of the most fundamental concepts — Callbacks. 👉 𝑾𝒉𝒚 𝒄𝒂𝒍𝒍𝒃𝒂𝒄𝒌𝒔? JavaScript is synchronous by default, but callbacks help us perform operations asynchronously — like API calls, timers, or event handling. ✔️ 𝑮𝒐𝒐𝒅 𝑷𝒂𝒓𝒕: Callbacks allow us to: Handle async operations smoothly Execute code only after a task is completed Build real-world flows like order → payment → confirmation 🛒 𝑬𝒙𝒂𝒎𝒑𝒍𝒆: 𝘊𝘳𝘦𝘢𝘵𝘦 𝘰𝘳𝘥𝘦𝘳 → 𝘗𝘳𝘰𝘤𝘦𝘦𝘥 𝘵𝘰 𝘱𝘢𝘺𝘮𝘦𝘯𝘵 → 𝘚𝘩𝘰𝘸 𝘴𝘶𝘮𝘮𝘢𝘳𝘺 → 𝘜𝘱𝘥𝘢𝘵𝘦 𝘸𝘢𝘭𝘭𝘦𝘵 ❌ But here’s the catch… 👉 1. 𝑪𝒂𝒍𝒍𝒃𝒂𝒄𝒌 𝑯𝒆𝒍𝒍 (𝑷𝒚𝒓𝒂𝒎𝒊𝒅 𝒐𝒇 𝑫𝒐𝒐𝒎) When callbacks are nested inside each other, the code becomes: Hard to read Difficult to debug Painful to maintain 👉 2. 𝑰𝒏𝒗𝒆𝒓𝒔𝒊𝒐𝒏 𝒐𝒇 𝑪𝒐𝒏𝒕𝒓𝒐𝒍 We pass our logic into another function (like an API), and: We lose control over when/if it's executed We blindly trust external code This can lead to unexpected bugs 💡 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠: Callbacks are powerful, but not scalable for complex flows. This is exactly why concepts like Promises and Async/Await were introduced. 🔥 Currently leveling up my async JS fundamentals step by step. Next stop → Promises! #JavaScript #AsyncJS #FrontendDevelopment #ReactJS #WebDevelopment #CodingJourney #Developers #LearningInPublic
To view or add a comment, sign in
-
-
Wrote a new blog on JavaScript Promises for Beginners Covering: - What problem promises actually solve - Promise states (pending, fulfilled, rejected) - How the promise lifecycle works - Handling success and errors properly - Promise chaining for cleaner async flows - Why promises improve code readability Most developers don’t struggle with async JavaScript because it’s complex. They struggle because of how it’s explained. This blog focuses on clarity over complexity. https://lnkd.in/gMuGYmm8 #JavaScript #WebDevelopment #Frontend #AsyncJavaScript #Promises #Coding #LearnToCode #100DaysOfCode
To view or add a comment, sign in
-
JavaScript isn’t asynchronous… the environment is. After diving deep into asynchronous JavaScript, I realized something that completely changed how I think about writing code: We don’t “wait” for data… we design what happens when it arrives. 💡 Most developers use fetch and Promises daily, but very few truly understand what happens under the hood. Here’s the real mental model: 🔹 JavaScript is single-threaded 🔹 Heavy operations (API calls, timers) are offloaded to Web APIs 🔹 fetch() returns a Promise immediately (not the data!) 🔹 .then() doesn’t execute your function… it registers it for later 🔥 The game changer? There are actually two queues, not one: Microtask Queue (Promises) → HIGH PRIORITY Callback Queue (setTimeout, etc.) And the Event Loop always prioritizes microtasks. 💥 Example: console.log("1"); setTimeout(() => console.log("2"), 0); Promise.resolve().then(() => console.log("3")); console.log("4"); 👉 Output: 1 . 4 . 3 . 2 🧠 Why this matters: Explains unexpected execution order Makes debugging async code 10x easier Helps avoid common interview pitfalls Builds a strong foundation for React & modern frontend ⚡ Key Insight: Promises are not about cleaner syntax… They are about controlling time and execution order in a non-blocking environment. 📌 Once you truly understand: Event Loop Microtask vs Callback Queue Promise lifecycle You stop guessing… and start predicting behavior. #JavaScript #Frontend #WebDevelopment #AsyncJS #Promises #EventLoop #React #Programming
To view or add a comment, sign in
-
-
🚀 𝐃𝐚𝐲 6 – 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩 (𝐒𝐢𝐦𝐩𝐥𝐞 & 𝐂𝐥𝐞𝐚𝐫) JavaScript is single-threaded… 👉 But then how does it handle things like `setTimeout`? 🤔 Let’s understand the real flow 👇 --- 💡 The Setup JavaScript uses: * Call Stack → runs code * Web APIs → handles async tasks * Callback Queue → waits for execution * Event Loop → manages everything --- 💡Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); --- 💡 Output: Start End Timeout --- 💡 Why? (Step-by-step) * `Start` → runs immediately * `setTimeout` → sent to Web APIs * `End` → runs immediately * Timer completes → callback goes to Queue * Event Loop checks → Stack empty * Callback pushed to Stack → executes --- ⚡ Key Insight 👉 Even with `0ms`, it does NOT run immediately 👉 It waits until the Call Stack is empty --- 💡 Simple Mental Model 👉 “Async code runs after sync code finishes” --- 💡 Why this matters? Because it explains: * execution order * async behavior * common bugs --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **Promises (Async Made Better)** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
To view or add a comment, sign in
-
-
JavaScript is easy. Until it isn't. 😅 Every developer has been there. You're confident. Your code looks clean. You hit run. And then: " Cannot read properties of undefined (reading 'map') " The classic JavaScript wall. Here are 7 JavaScript mistakes I see developers make constantly and how to fix them: 1. Not understanding async/await ⚡ → Wrong: | const data = fetch('https://lnkd.in/dMDBzbsK'); console.log(data); // Promise {pending} | → Right: | const data = await fetch('https://lnkd.in/dMDBzbsK'); | 2. Using var instead of let/const → var is function scoped and causes weird bugs → Always use const by default. let when you need to reassign. Never var. 3. == instead of === → 0 == "0" is true in JavaScript 😱 → Always use === for comparisons. Always. 4. Mutating state directly in React → Wrong: user.name = "Shoaib" → Right: setUser({...user, name: "Shoaib"}) 5. Forgetting to handle errors in async functions → Always wrap await calls in try/catch → Silent failures are the hardest bugs to track down 6. Not cleaning up useEffect in React → Memory leaks are real → Always return a cleanup function when subscribing to events 7. Treating arrays and objects as primitives → [] === [] is false in JavaScript → Reference types don't compare like numbers — learn this early JavaScript rewards the developers who understand its quirks. 💡 Which of these caught YOU off guard when you first learned it? 👇 #JavaScript #WebDevelopment #Frontend #FullStackDeveloper #React #Programming #CodingTips #Developer #Tech #Pakistan #LearnToCode #JS #SoftwareEngineering #100DaysOfCode #PakistaniDeveloper
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development