🚀 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
Predictable Error Handling with try-fetch-catch
More Relevant Posts
-
This async / await output confuses even experienced developers 😲 🧩 JavaScript Output-Based Question (Async / Await) ✅ Correct Output 3 1 4 2 🧠 Why this output comes? (Step-by-Step) 1️⃣ Synchronous code runs first • console.log(3) → prints 3 2️⃣ test() is called • console.log(1) runs immediately → prints 1 3️⃣ await Promise.resolve() • Even though the promise is resolved, await pauses the function execution • Remaining code moves to the microtask queue 4️⃣ Back to synchronous code • console.log(4) → prints 4 5️⃣ Microtasks execute • console.log(2) runs last → prints 2 🔑 Key Takeaways (Interview Insight) ✔️ await is always asynchronous ✔️ Code after await runs in the microtask queue ✔️ Even resolved promises don’t run immediately ✔️ Understanding the event loop is critical for async JavaScript async / await looks synchronous, but behaves asynchronously. #JavaScript #AsyncAwait #InterviewQuestions #FrontendDeveloper #MERNStack #ReactJS
To view or add a comment, sign in
-
-
🚀 Understanding the Node.js Event Loop — Where Your Code Really Runs Ever wondered why `setTimeout`, `Promises`, and `setImmediate` don’t run in the same order? The answer lies in the Node.js Event Loop phases. This visual breaks down exactly where common JavaScript APIs execute: 🔹 `console.log` → Synchronous 🔹 `process.nextTick()` → Microtask (highest priority) 🔹 `Promise.then()` → Microtask 🔹 `setTimeout / setInterval` → Timers phase 🔹 `fs.readFile`, HTTP, DB queries → Poll phase 🔹 `setImmediate()` → Check phase 🔹 `socket.on('close')` → Close callbacks 👉 Key takeaway: **Microtasks** always run before moving to the next event loop phase — this is why execution order can surprise you in interviews and real projects. If you’re preparing for Node.js interviews or building high-performance backend systems, mastering the event loop is non-negotiable. 💬 Drop a comment if you want: * Tricky event loop output questions * Browser vs Node.js event loop comparison * Async/Await deep dive #NodeJS #JavaScript #BackendDevelopment #WebDevelopment #EventLoop #AsyncProgramming #SoftwareEngineering #InterviewPreparation #TechLearning
To view or add a comment, sign in
-
-
👨💻 TypeScript Review Question: Function Length. I worked on a question that asked me to implement a function called functionLength that returns the number of parameters a function expects. This question is very straightforward once you understand what the .length data property does. In JavaScript, every function has a built-in .length property. ✍️ This question serves as a helpful prerequisite for currying problems. In currying problems, you often need to know how many arguments a function expects before deciding to execute it or keep returning partial functions. 🧠 #JavaScript #WebDevelopment #Frontend #SoftwareEngineering #TypeScript
To view or add a comment, sign in
-
-
Day 62 of me reading random and basic but important dev topicsss..... Today I read about the Resource Loading in JavaScript...... In our day-to-day work building interfaces with React or other modern frameworks, it's easy to take module bundlers for granted. But what happens when we need to dynamically inject a third-party script......like an analytics tracker, a payment SDK, or a support widget.....on the fly? Understanding the vanilla DOM events onload and onerror is a must for any robust front-end architecture. 1. The Dynamic Injection Adding a script dynamically is straightforward: let script = document.createElement('script'); script.src = "third-party.js"; document.head.append(script); But we can't just invoke its functions immediately. The browser needs time to fetch and execute it. 2. script.onload (The Success Path) This event triggers after the script has successfully loaded and executed. This is our green light to safely use the newly available variables or functions. 3. script.onerror (The Failure Path) If the script 404s or the server is down, onerror catches it. However, keep in mind: we won't get HTTP status codes (like 404 or 500) here, just a notification that the network request failed. Loading vs. Execution Here is where we get tripped up: onload and onerror only track the network loading phase. If a script downloads successfully but contains a syntax or runtime error during execution, onload will still fire! To catch those internal execution bugs, we need a different tool entirely: the window.onerror global handler. Keep Learning!!!!! #JavaScript #WebDevelopment #FrontendDev #React #SoftwareEngineering
To view or add a comment, sign in
-
-
Node.js – Day 4/30 Single-Threaded & Event-Driven Model One common misconception is that single-threaded means slow. In Node.js, it actually means efficient. Node.js runs JavaScript on a single main thread, but it uses an event-driven model to handle multiple requests. How this works: Incoming requests are registered as events Time-consuming tasks (DB, file I/O, network calls) are handled asynchronously Once completed, callbacks are pushed back to be executed Because Node.js doesn’t block the main thread: It can handle many users at the same time Resources are used efficiently Performance remains stable under load This is why Node.js is well-suited for I/O-heavy applications like APIs and real-time systems. Learning this cleared up a lot of confusion for me about Node.js performance. #NodeJS #BackendDevelopment #JavaScript #EventDriven #LearningInPublic
To view or add a comment, sign in
-
Ever encountered a JavaScript bug where your array mysteriously loses elements? 😳 Picture this: you're using `splice` to remove an item, but your entire array gets scrambled in production. I faced this when a `for...in` loop, meant for objects, was mistakenly used for arrays. Here's a simple example: ```javascript const arr = [1, 2, 3, 4]; for (let i in arr) { arr.splice(i, 1); } ``` In theory, you'd expect the loop to remove elements one by one. But the index shifts during each `splice`, causing skipped elements and unexpected outcomes. This little oversight can wreak havoc, especially if your array processing is complex. Why's it hard to spot? It's subtle. Your tests might pass with small data, but crash and burn with real-world inputs. Fix it by switching to a `for...of` loop or using array methods like `filter`. It ensures you process elements without altering the loop index mid-execution. This simple change made our code robust! Have you stumbled upon similar JavaScript quirks? Share your experiences! 👇 #JavaScript #Debugging #CodingProblems #JavaScript #Debugging #CodingProblems
To view or add a comment, sign in
-
𝗪𝗲𝗹𝗰𝗼𝗺𝗲 𝘁𝗼 𝗗𝗮𝘆 𝟴 Have you ever seen JavaScript behave correctly… but still give the wrong output? 🤔 𝘉𝘦𝘧𝘰𝘳𝘦 𝘴𝘤𝘳𝘰𝘭𝘭𝘪𝘯𝘨, 𝘨𝘶𝘦𝘴𝘴 𝘵𝘩𝘦 𝘰𝘶𝘵𝘱𝘶𝘵 𝘰𝘧 𝘵𝘩𝘪𝘴 𝘴𝘪𝘮𝘱𝘭𝘦 𝘤𝘰𝘥𝘦 𝚏𝚘𝚛 (𝚟𝚊𝚛 𝚒 = 𝟷; 𝚒 <= 𝟹; 𝚒++) { 𝚜𝚎𝚝𝚃𝚒𝚖𝚎𝚘𝚞𝚝(() => { 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚒); }, 𝟷𝟶𝟶𝟶); } 𝗘𝘅𝗽𝗹𝗲𝗰𝘁𝗲𝗱 1, 2, 3 𝗔𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗿𝗲𝘀𝘂𝗹𝘁 4,4,4 𝗧𝗵𝗶𝘀 𝗶𝘀 𝗮 𝗰𝗹𝗼𝘀𝘂𝗿𝗲 𝗯𝘂𝗴 — 𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗰𝗼𝗺𝗺𝗼𝗻 (𝗮𝗻𝗱 𝗰𝗼𝗻𝗳𝘂𝘀𝗶𝗻𝗴) 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗽𝗶𝘁𝗳𝗮𝗹𝗹𝘀. 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗛𝗮𝗽𝗽𝗲𝗻𝘀 • var is function-scoped • setTimeout creates a closure • All callbacks reference the same variable i • When they execute, the loop has already finished Closures don’t capture values — they capture references. 𝗧𝗵𝗲 𝗙𝗶𝘅 𝚏𝚘𝚛 (𝚕𝚎𝚝 𝚒 = 𝟷; 𝚒 <= 𝟹; 𝚒++) { 𝚜𝚎𝚝𝚃𝚒𝚖𝚎𝚘𝚞𝚝(() => { 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚒); }, 𝟷𝟶𝟶𝟶); } 𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝘄𝗼𝗿𝗸𝘀: • let is block-scoped • Each iteration gets its own binding • Each closure remembers a different i 𝗬𝗼𝘂’𝗹𝗹 𝘀𝗲𝗲 𝘁𝗵𝗶𝘀 𝗽𝗮𝘁𝘁𝗲𝗿𝗻 𝗶𝗻: • Event handlers • Async loops • API callbacks • Timers • React effects If you don’t understand closures, You don’t see the bug — you just debug longer. #JavaScript #JSFundamentals #Closures #FrontendDevelopment #WebDevelopment #BugFixing #ReactJS #LearningInPublic
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
-
-
Have you ever been baffled by TypeScript's type narrowing, only to find out the problem isn't where you first look? 🤔 A couple of weeks ago, I was dealing with a subtle bug. The symptom was simple: a type error that would disappear under one condition but reappear under another without any obvious changes in logic. Here's a snippet that highlights the issue: ```typescript function processInput(input: string | number) { if (typeof input === 'string') { // Do something with the string } // More code that should only be applicable if input is a number console.log(input.toFixed(2)); } ``` In this scenario, TypeScript's type narrowing is expected to "forget" about `input` being a string after the `if` block. But, if additional complex structures or nested functions interact within the `if`, TypeScript can sometimes lose track, and you'll be stuck debugging an input type mismatch. The real headache? This problem rarely shows up in tests and is more likely to cause havoc when you upgrade TypeScript versions, since improvements can introduce new, stricter checks. To fix it, you can use an explicit type guard: ```typescript function isNumber(input: unknown): input is number { return typeof input === 'number'; } function processInput(input: string | number) { if (isNumber(input)) { // Guaranteed to be a number here console.log(input.toFixed(2)); } } ``` Always handle type assertions carefully, and regularly review your TypeScript configuration when upgrading. Have you come across similar issues? Share your experiences below! #TypeScript #JavaScript #CodeDebugging #WebDevelopment #SoftwareEngineering #TypeScript #JavaScript #CodeDebugging #WebDevelopment #SoftwareEngineering
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
-
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