Finally, asynchronous code that reads like synchronous code. 📖✨ We started with 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤𝐬 (The Pyramid of Doom). 🏔️ We moved to 𝐏𝐫𝐨𝐦𝐢𝐬𝐞𝐬 (The Chain). 🔗 Now, we have the ultimate evolution: 𝐀𝐬𝐲𝐧𝐜/𝐀𝐰𝐚𝐢𝐭. 🚀 Async/await is essentially "syntactic sugar" built on top of Promises, but it completely changes how we write and read code. 𝐓𝐡𝐞 𝐁𝐫𝐞𝐚𝐤𝐝𝐨𝐰𝐧: 1️⃣ `async` 𝐊𝐞𝐲𝐰𝐨𝐫𝐝: • You place this before a function definition. • It automatically wraps the function's return value in a Promise. 2️⃣ `await` 𝐊𝐞𝐲𝐰𝐨𝐫𝐝: • This is the magic "Pause" button. ⏸️ • It tells the JavaScript engine: "𝑆𝑡𝑜𝑝 𝑒𝑥𝑒𝑐𝑢𝑡𝑖𝑛𝑔 𝑡ℎ𝑖𝑠 𝑓𝑢𝑛𝑐𝑡𝑖𝑜𝑛 𝑟𝑖𝑔ℎ𝑡 ℎ𝑒𝑟𝑒. 𝑊𝑎𝑖𝑡 𝑓𝑜𝑟 𝑡ℎ𝑒 𝑃𝑟𝑜𝑚𝑖𝑠𝑒 𝑡𝑜 𝑟𝑒𝑠𝑜𝑙𝑣𝑒. 𝑂𝑛𝑐𝑒 𝑖𝑡 𝑔𝑖𝑣𝑒𝑠 𝑚𝑒 𝑡ℎ𝑒 𝑣𝑎𝑙𝑢𝑒, 𝑠𝑡𝑜𝑟𝑒 𝑖𝑡 𝑖𝑛 𝑡ℎ𝑖𝑠 𝑣𝑎𝑟𝑖𝑎𝑏𝑙𝑒 𝑎𝑛𝑑 𝑚𝑜𝑣𝑒 𝑡𝑜 𝑡ℎ𝑒 𝑛𝑒𝑥𝑡 𝑙𝑖𝑛𝑒." 𝐖𝐡𝐲 𝐢𝐬 𝐢𝐭 𝐛𝐞𝐭𝐭𝐞𝐫? • 𝐑𝐞𝐚𝐝𝐚𝐛𝐢𝐥𝐢𝐭𝐲: You read the code top-to-bottom, just like normal synchronous code. No more jumping between `.then()` blocks. • 𝐄𝐫𝐫𝐨𝐫 𝐇𝐚𝐧𝐝𝐥𝐢𝐧𝐠: You can use the standard `try...catch` block that you use for regular code! No need for a separate `.catch()` method attached to the end. Check out the visual example below to see how clean the syntax looks! 👇 Do you still use `.then()` chains in some places, or is it `async/await` everywhere now? #JavaScript #WebDevelopment #AsyncJS #CleanCode #SoftwareEngineering #Frontend
Nidhi Jagga’s Post
More Relevant Posts
-
Stop Writing Try-Catch Blocks Everywhere: Meet the catchAsync Helper 🛠️ Building an Express.js backend? You're probably stuck writing try-catch blocks in all your controllers. It probably looks something like this: In JavaScript: try { // your code } catch (error) { next(error); } Doing this again and again makes your code a pain. My solution? A Higher-Order Function (HOF) called catchAsync. What's catchAsync? It's a simple function that wraps your async request handlers. It writes the try-catch for you automatically, so you don't have to. If something goes wrong, it catches it and sends it to your error handler using next(err). Why is this so helpful? * No More Copy-Pasting: Stop typing the same error handling code in every API route. * Controllers are Cleaner: Your code is easier to read, showing only logic that's important. * Consistent: Every error is caught and handled the same way everywhere. * Easier to Update: Change error handling in one place. What's a Higher-Order Function? It's just a function that takes another function as an argument or returns a new function. catchAsync takes your controller function, adds error-handling, and returns it. Using tools like this makes a project better. It saves time, reduces bugs, and keeps your code clean. Please see the code in the image below. #NodeJS #ExpressJS #BackendDevelopment #CleanCode #JavaScriptTips #TypeScript #WebDevelopment #SoftwareArchitecture
To view or add a comment, sign in
-
-
Async/await isn't magic. It's just promises with cleaner syntax. Spent way too long thinking async/await was some completely different thing. It's not. It's syntactic sugar over promises. The key insight? Only the function gets suspended, not JavaScript itself. When you hit await, that function pauses and gets removed from the call stack. But JavaScript keeps running everything else. When the promise resolves, the event loop brings your function back and it continues from where it left off. --- async function fetchData() { console.log("Start"); const data = await getData(); // Function pauses HERE console.log(data); } fetchData(); console.log("Outside"); // This runs while fetchData waits! // Output: // Start // Outside (runs immediately!) // (data... after promise resolves) --- Two mistakes I made constantly: 1. Sequential when I meant parallel - Multiple awaits run one after another. If you want them to run together, start them all first, then await them. 2. Forgetting everything is still promises - Async functions always return promises. await just unwraps them. Behind the scenes, it's all .then() chains. Documented the execution flow with examples: https://lnkd.in/dDqtxdnD Thanks to Akshay Saini 🚀 and Namaste JavaScript for explaining how async/await actually works under the hood. What confused you most about async/await? Let me know if I missed anything - happy to improve it. #JavaScript #WebDev #Coding #100DaysOfCode #LearningInPublic
To view or add a comment, sign in
-
Most devs “use” Promises long before they actually understand them. I was the same. Then I started digging and it finally clicked. The moment you get that JavaScript is single threaded, Promises make sense. JS can only do one thing at a time, so if you wait for an API or a database call synchronously, the whole page would stall. Promises give JS a way to kick off that slow task, keep the main thread free, and notify you later when the result is ready. That’s the real mental model: a Promise is simply a placeholder for a future value. While it’s pending, your code keeps moving. Once it either resolves or rejects, you choose what to do next. From there, the different pieces feel natural: • then handles success • catch handles failure • finally runs either way for cleanup Fetch is a great example. It returns a Promise, so you chain then calls to work with the response, convert it to JSON, and pass it down the chain. If something breaks, catch is your safety net. This mirrors how async operations actually behave in the real world. Async/await is just a cleaner way to write the same flow. Mark a function async, await the result, wrap it in try/catch if you expect errors, and use finally for cleanup. Both styles matter, because teams and libraries use both. If you’re still memorizing syntax, here’s the quiet truth: learning the mental model is what makes Promises feel intuitive instead of magical. Once that clicks, everything else is just mechanics. Curious, did you learn Promises from a tutorial, from debugging pain or from async/await first? #Javascript #async #await #promise #concepts
To view or add a comment, sign in
-
#JS_Core (3 of 7) How can #Single_Threaded_Language handle 5 API calls "simultaneously" ?? The truth is, it doesn't. Our single threaded language JavaScript is not a worker but a coordinator Here is what happens under the hood when you trigger an async task - > JS hands off tasks (Timers, Network calls, File I/O) to the environment (Browser APIs or Libuv in Node.js). > It keeps executing your synchronous code immediately. The main thread is never blocked by the "waiting." > Once the environment finishes the task, the Event Loop pushes the result back into the execution queue to be processed. To orchestrate this chaos, we have modern Promise methods as: > .all : Waits for all to succeed. If one fails, the whole operation rejects. > .allSettled : It Waits for everything to finish, regardless of success or failure. > .any : It returns the first promise that succeeds (unless they all fail). > .race : It returns the result of the very first promise to settle #JavaScript #NodeJS #EventLoop #AsyncAwait #SoftwareEngineering #WebDev
To view or add a comment, sign in
-
-
🚀 Just open-sourced my daily driver for clean JS/TS error handling In JavaScript, error handling often ends up fragmented: ❌ try/catch blocks everywhere ❌ Manual response.ok checks ❌ JSON parsing that can throw at runtime try-fetch-catch brings Go-style error handling to JS/TS by replacing thrown exceptions with predictable tuples. ✨ What it gives you: 🌐 tryFetch — a drop-in fetch replacement that returns [error, data, response] 🛠️ tryCatch — wraps any sync or async function and returns [error, result] 🚫 No thrown exceptions ➡️ Linear, readable control flow 📦 Native ESM + CommonJS builds 🪶 Zero dependencies Example: const [err, user] = await tryFetch("/api/users/123"); if (err) // handle renderUser(user); // user is safe to consume If you care about predictable control flow, typed errors, and less boilerplate, this might be useful. 📦 npm: 🔗 https://lnkd.in/eqBESSWC 💬 Feedback welcome — especially from folks who’ve wrestled with fetch error handling before. #opensource #javascript #typescript #webdev #nodejs
To view or add a comment, sign in
-
🧠 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗮𝗹 𝗚𝗲𝗻𝗲𝗿𝗶𝗰𝘀 𝗶𝗻 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 — 𝘁𝗵𝗮𝘁 𝘄𝗲𝗶𝗿𝗱 <𝗧> 𝘆𝗼𝘂’𝘃𝗲 𝘀𝗲𝗲𝗻 If you’ve ever opened a library you already use, you’ve probably seen something like <T> and thought: what is this weird thing? 𝗧𝗵𝗮𝘁’𝘀 𝗮 𝗚𝗲𝗻𝗲𝗿𝗶𝗰. 🔹 𝗪𝗵𝗮𝘁 𝗮 𝗴𝗲𝗻𝗲𝗿𝗶𝗰 𝗿𝗲𝗮𝗹𝗹𝘆 𝗶𝘀 In TypeScript, a generic means “the type will be decided later”. Instead of locking a function, hook, or service to one type, you describe a 𝗿𝗲𝗹𝗮𝘁𝗶𝗼𝗻𝘀𝗵𝗶𝗽: what goes in is the same shape that comes out. A generic lets the caller choose the type, while your function, hook, or service 𝗴𝘂𝗮𝗿𝗮𝗻𝘁𝗲𝗲𝘀 𝗰𝗼𝗻𝘀𝗶𝘀𝘁𝗲𝗻𝗰𝘆. If something goes in as T, it comes out as T. No guessing. No casting. 🔹 𝗥𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝘂𝘀𝗲 𝗰𝗮𝘀𝗲𝘀 Generics shine in real use cases like Hooks (useFetch<T>), services, repositories, and shared utilities. They keep input and output aligned, reduce duplication, and prevent unsafe assumptions. 🔹 𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝗺𝗮𝘁𝘁𝗲𝗿𝘀 Generics reduce bugs, improve readability, and make abstractions safer. You stop writing defensive code and let the type system enforce intent. Good generics don’t add complexity. 𝗧𝗵𝗲𝘆 𝗿𝗲𝗺𝗼𝘃𝗲 𝘂𝗻𝗰𝗲𝗿𝘁𝗮𝗶𝗻𝘁𝘆. Even if you don’t write them often, understanding generics helps you design cleaner, smarter APIs. 💬 Where have generics helped you the most — or when did <T> finally click for you? #TypeScript #JavaScript #SoftwareEngineering #CleanCode #DeveloperExperience #ProgrammingConcepts #CodeQuality #React #NodeJS #WebDevelopment
To view or add a comment, sign in
-
🟨 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗗𝗮𝘆 𝟰𝟵: 𝗜𝗻𝘃𝗲𝗿𝘀𝗶𝗼𝗻 𝗼𝗳 𝗖𝗼𝗻𝘁𝗿𝗼𝗹 (𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺) In JavaScript, we often use callbacks to handle async tasks — API calls, timers, or events. But callbacks introduce a hidden issue called Inversion of Control. 🔹 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗮 𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸? A callback is a function passed to another function and executed later. 𝘴𝘦𝘵𝘛𝘪𝘮𝘦𝘰𝘶𝘵(() => { 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨("𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵"); }, 1000); 🔹 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗜𝗻𝘃𝗲𝗿𝘀𝗶𝗼𝗻 𝗼𝗳 𝗖𝗼𝗻𝘁𝗿𝗼𝗹? When we pass a callback, we give control of our code to another function. We don’t control: • When it runs • How many times it runs • Whether it runs at all 🔹 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 𝘢𝘱𝘪.𝘤𝘳𝘦𝘢𝘵𝘦𝘖𝘳𝘥𝘦𝘳(𝘤𝘢𝘳𝘵, 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 () { 𝘢𝘱𝘪.𝘱𝘳𝘰𝘤𝘦𝘦𝘥𝘛𝘰𝘗𝘢𝘺𝘮𝘦𝘯𝘵(); }); Here: • proceedToPayment is our code • createOrder decides when it runs • Our callback executes only when the API decides, based on its internal logic or async events. This is Inversion of Control in action. 🔹 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗜𝘀 𝗮 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 • Unexpected behavior • Harder debugging • Leads to callback hell in large apps 🔹 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻 Promises and async / await keep control in our hands. 🔹 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 Callbacks give control away. Promises bring it back. 💬 GitHub link in the comments for examples #JavaScript #Day49 #100DaysOfCode #Frontend
To view or add a comment, sign in
-
Synchronous vs Asynchronous | Why JavaScript (and Node.js) Chose Async? 👉Synchronous: Execution: Synchronous code executes sequentially, line by line, in a blocking manner. Each operation must complete before the next one can begin. Call Stack: Operations are placed onto the call stack, and the JavaScript engine processes them one at a time. Blocking: If a synchronous operation is time-consuming it will block the main thread, preventing other code from executing and potentially causing the user interface to become unresponsive. 👉Asnychronous: Execution: Asynchronous code allows operations to run independently without blocking the main thread. While waiting for a time-consuming task to complete, other code can continue to execute. Non-Blocking: This approach is crucial for tasks like network requests (fetching data from an API), file operations, or timers, which might take a variable amount of time. How Async Works in JavaScript / Node.js? -- Async tasks (I/O, timers, DB calls) run in the background -- Results are queued -- The Event Loop executes them when ready -- The main thread stays free #JavaScript #NodeJS #BackendDevelopment #AsyncProgramming #WebDevelopment #MERNStack #EventLoop #CleanCode #SoftwareEngineering #100DaysOfCode
To view or add a comment, sign in
-
🌐 Fetch API + Error Handling in JavaScript (The Right Way) Using fetch() is easy. Handling errors correctly is what separates beginners from good developers. Many people think fetch throws an error for failed HTTP calls — it doesn’t. You must handle it explicitly. 🧠 Key Insight fetch() only rejects on network failure HTTP errors like 404 or 500 must be checked manually 🚀 Why This Matters Prevents broken UI states Makes debugging easier Production-ready API handling Very common interview scenario 💡Tip If asked: “Does fetch throw error on 404?” Correct answer: 👉 No. You must check response.ok yourself. Proper error handling prevents silent failures in production #JavaScript #FetchAPI #ErrorHandling #Frontend #WebDevelopment #Coding #InterviewPrep
To view or add a comment, sign in
-
-
Full Article & Code Samples: https://lnkd.in/gYBchTs8 Stop awaiting your performance away. 🛑 Are you still running independent API calls sequentially? const user = await fetchUser(); (1s) const posts = await fetchPosts(); (1s) Total: 2 seconds. By mastering Promise.all() and Promise.allSettled(), you can drop that time to 1 second. My latest blog breaks down the Async Essentials: ✅ The 3 Eras: Callbacks ➡️ Promises ➡️ Async/Await. ✅ Resilience: How to handle timeouts with Promise.race(). ✅ The for...of Trap: Why forEach fails with async code. ✅ Best Practices: My checklist for shipping reliable async logic. Level up your JavaScript internals today. #NodeJS #CodingTips #FullStack #JavaScript #CleanCode
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