Day 7 #100DaysOfCode 💻 Today I learned Using async/await instead of then() with fetch. Normally we do: fetch('https://lnkd.in/gAwJs9UG') .then(res => res.json()) .then(data => console.log(data)); Better approach with async/await: async function getData() { try { const res = await fetch('https://lnkd.in/gAwJs9UG'); const data = await res.json(); console.log(data); } catch(err) { console.error(err); } } getData(); ✨ Reflection: Async/await makes code cleaner, easier to read, and simpler for error handling. #javascript #asyncawait #webdevelopment #100DaysOfCode #Akbiplob
Learn Async/Await with JavaScript
More Relevant Posts
-
Day 8 #100DaysOfCode 💻 Today I learned how to add a loading spinner before fetching API data. When we fetch data from an API, it may take some time. To improve user experience, we can show a loading spinner while the data is loading and hide it after the data is received. Simple example: function showLoading(){ document.getElementById("spinner").classList.remove("hidden"); } function hideLoading(){ document.getElementById("spinner").classList.add("hidden"); } showLoading(); fetch("https://lnkd.in/gAwJs9UG") .then(res => res.json()) .then(data => { console.log(data); hideLoading(); }) .catch(error => { console.log(error); hideLoading(); }); Small improvement, but it makes the UI feel much more professional. #100DaysOfCode #JavaScript #WebDevelopment #FrontendDevelopment #API #LearningInPublic #Akbiplob
To view or add a comment, sign in
-
Day 92 of me reading random and basic but important dev topicsss..... Today I read about the modern Fetch API.... If you are still reaching for XMLHttpRequest or unnecessarily bundling heavy external libraries for simple network calls, it's time to leverage the native power of fetch(). It’s modern, versatile, and built directly into all modern browsers. Here is everything every dev need to know about the anatomy of a Fetch request. 1. The Two-Stage Process Getting a response with fetch() isn't a single step; it’s a two-stage promise resolution: Stage 1: The Headers Arrive The promise returned by fetch(url) resolves with a Response object the moment the server responds with headers - before the full body downloads. This is where you check the HTTP status. Note: A 404 or 500 error does NOT reject the promise. A fetch promise only rejects on network failures. Always check response.ok (returns true for 200-299 statuses) or response.status! Stage 2: Reading the Body To actually get the data, you need to call an additional promise-based method on the response. Fetch gives you multiple ways to parse the body: * response.json() - parses as JSON (most common) * response.text() - returns raw text * response.blob() - for binary data with types (like downloading an image) * response.formData() - for multipart/form-data * response.arrayBuffer() - for low-level binary data 2. The Already Consumed Trap Here is a classic gotcha that trips up many developers: We can only read the body once. If we call await response.text() to debug or log the output, and then subsequently call await response.json(), your code will fail. The stream has already been consumed! Summary of a standard GET request: let response = await fetch('https://lnkd.in/e4utYKVK'); if (response.ok) { let data = await response.json(); console.log(data); } else { console.error("HTTP-Error: " + response.status); } Keep Learning!!!! #JavaScript #WebDevelopment #SoftwareEngineering #FetchAPI #FrontendDev
To view or add a comment, sign in
-
-
Just published a new video in my Web Development Series 🚀 This time I covered Request Data Handling in Express.js in a very simple and beginner-friendly way. If you are learning backend development, this is a must-know topic. I explained: • req.params • req.query • req.body • And built a simple CRUD API Everything with easy examples so you can understand clearly even if you're starting for the first time. Check it out and let me know your feedback 👇 https://lnkd.in/g76RMnBt #webdevelopment #nodejs #expressjs #backenddevelopment #javascript #coding #learnprogramming
Request Data Handling in Express.js | req.params, req.query, req.body Explained | CRUD API
https://www.youtube.com/
To view or add a comment, sign in
-
This pattern is everywhere: useEffect(() => { setLoading(true); fetch('/api/data') .then(r => r.json()) .then(setData) .catch(setError) .finally(() => setLoading(false)); }, []); Problems: ❌ No caching ❌ Race conditions ❌ Manual loading/error state ❌ No background refetch ❌ Stale data on re-focus Use TanStack Query: const { data, isLoading } = useQuery({ queryKey: ['data'], queryFn: fetchData }); All problems solved. Your future self will thank you. #ReactNative #JavaScript #CleanCode #ReactQuery #MobileDev
To view or add a comment, sign in
-
A common TypeScript anti-pattern I keep seeing. When working with nested arrays, many developers lean on optional chaining everywhere, especially inside loops. It feels safe. It feels concise. But it quietly introduces unnecessary branching and noisy logic. --- 🛡️ The “defensive everywhere” approach ``` function getActiveEmails(data?: ApiResponse) { return data?.users ?.filter(u => u?.isActive) ?.map(u => u?.profile?.email ?? "no-email") ?? []; } ``` What’s happening here? - "data?.users" → branch - "u?.isActive" → branch per iteration - "u?.profile?.email" → multiple branches per iteration - "?? []" → fallback branch You’ve now created a combinatorial explosion of paths inside what should be a simple transformation. Your tests? They now need to cover: - missing "data" - missing "users" - partially invalid users - missing profiles - missing emails All implicitly baked into one chain. --- ✅ Early return & controlled assumptions ``` function getActiveEmails(data?: ApiResponse) { if (!data?.users) return []; return data.users .filter(user => user.isActive) .map(user => user.profile.email); } ``` Key differences: - The guard ("if") still uses optional chaining, but only once, at the boundary - Inside the loop, we treat data as valid by contract - No defensive noise inside "filter"/"map" - The “happy path” is clean and linear --- Why? Optional chaining inside iteration is especially costly: - It introduces branches per element - It hides data contract issues - It bloats test cases unnecessarily - It makes bugs harder to spot (everything just becomes “undefined”) --- So, - Use optional chaining at the edges of your system - Use early returns to establish guarantees - Keep your core logic branch light and explicit --- Optional chaining isn’t the problem. Unstructured defensiveness is. #TypeScript #JavaScript #CleanCode #CodeQuality #Refactoring #BestPractices #DeveloperTips
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗙𝗮𝗦𝗧𝗲𝗦𝗧 𝗖𝗼𝗱𝗲 𝗦𝗲𝗮𝗿𝗰𝗵 𝗧𝗼𝗼𝗹 You need to find patterns in your codebase. Maybe it's leftover console.log calls or renaming a variable across hundreds of files. You could use find-and-replace, but it only matches text. It doesn't understand code. What you really want is a tool that understands the structure of your code. These are called structural code search tools. They parse your code into a tree, then let you match against the shape of the code rather than its raw text. I tested five popular options: - ast-grep - GritQL - semgrep - jscodeshift - recast I generated 500 JavaScript and TypeScript files and ran three tasks: - Simple search: find every console.log call - Code transformation: change every var to const - Complex search: find async functions with try/catch blocks Here are the results: - ast-grep is 5x faster than the next fastest tool and uses a fraction of the memory. - ast-grep processed 500 files in roughly the time it takes you to blink. - The speed gap widens on harder tasks. I used tree-sitter, a parsing library, and Rust to build ast-grep. It's focused on structural search and replace. You can run the benchmark code on your own machine: https://lnkd.in/gKzHVJR6 Source: https://lnkd.in/g34pEFrE
To view or add a comment, sign in
-
📘 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐌𝐨𝐝𝐮𝐥𝐞 (𝐁𝐚𝐬𝐢𝐜) 𝐒𝐞𝐜𝐭𝐢𝐨𝐧 2: 𝐕𝐚𝐫𝐢𝐚𝐛𝐥𝐞𝐬 1.What is a variable? 2.Why do we use a variable? 3.How to declare a variable? 4.Tell me about variable declaration rules? 5.How many types of variables do you know? 6.When do we use var? 7.When do we use let? 8.When do we use const? 9.How to create an undefined variable? 10.What is an undefined variable? 11.What is undefined? 12.What is NaN? 13.What is null? 14.What is concatenation? 15.What is Infinity? 16.How to assign data to a variable / How to assign a variable data? 17.Variable is primitive or non-primitive? 🎯 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧𝐬 (𝐄𝐱𝐭𝐫𝐚) 1.Difference between var, let, and const? 2.What is variable hoisting? 3.Why can var be accessed before declaring it? 4.What is temporal dead zone (TDZ)? 5.Can we reassign const variable? 6.Why shouldn't modern JavaScript use var? 𝐒𝐞𝐜𝐭𝐢𝐨𝐧 3: 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐃𝐚𝐭𝐚 𝐓𝐲𝐩𝐞𝐬 & 𝐊𝐞𝐲𝐰𝐨𝐫𝐝𝐬 1.JavaScript data types? 2.What is a reserved keyword? 3.What is a special keyword? 4.How can check type data type? 5.JavaScript variables is case-sensitive? 6.JavaScript variable naming conventions? 7.How to convert string ("20") to number (20)? 8.JavaScript built-in functions? 🎯 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧𝐬 (𝐄𝐱𝐭𝐫𝐚) 1.Difference between primitive and reference types? 2.What is type coercion? 3.Difference between null and undefined? 4.What is typeof null / What is the output of typeof null and why? (Important trick question) 5.What is the difference in memory management between primitive and reference type data? #DotNet #AspNetCore #MVC #FullStack #SoftwareEngineering #ProgrammingTips #DeveloperLife #LearnToCode #JavaScript #JS #JavaScriptTips #JSLearning #FrontendDevelopment #WebDevelopment #CodingTips #CodeManagement #DevTools
To view or add a comment, sign in
-
-
How API Fetch Works in JavaScript Today I explored fetching data from APIs in JavaScript. Here’s the core idea: const response = await fetch('https://lnkd.in/gtuyqVPs'); const data = await response.json(); console.log(data); Key takeaways: fetch() → request data from an API async/await → makes async code readable response.json() → converts data to usable objects Fun tip: I even visualized this in a colorful notebook-style page with doodles, icons, and notes. It really helps to understand the flow of data! #JavaScript #WebDev #API #CodingTips #LearningByDoing #TechNotes
To view or add a comment, sign in
-
-
I got tired of debugging API issues with console.log(). After one too many late nights staring at: POST /api/orders 500 8ms ...with zero context about what was in the request body, what the response said, or which user triggered it — I built something better. Introducing reqlog — a live HTTP request dashboard for NestJS, Express and Fastify. Drop it in as middleware and a dashboard opens at localhost:9000 showing every request in real time: → Full request + response body → Payload diff between requests → One-click request replay → Slow request highlighting → Zero config, zero persistence NestJS setup is literally 3 lines: import { ReqlogModule } from 'reqlog-nestjs' @Module({ imports: [ReqlogModule.forRoot()] }) // dashboard opens automatically I use this daily at Softylines across 45+ microservices. It replaced a debugging workflow that was costing my team hours every week. MIT licensed. Open source. Free forever. GitHub → https://lnkd.in/dzXM6BrK If you've ever added a console.log at 11pm in frustration — this one's for you. ⭐ #nodejs #nestjs #opensource #javascript #devtools #webdev
To view or add a comment, sign in
-
-
5 TypeScript patterns I copy into every new project. Steal these. 1. Strict null checks everywhere tsconfig: "strictNullChecks": true Forces you to handle undefined. Catches bugs before runtime. Non-negotiable. 2. Utility types for API responses type ApiResponse<T> = { data: T; error: string | null; loading: boolean; } Consistent shape for every API call. Components always know what to expect. 3. Discriminated unions for state type State = | { status: 'loading' } | { status: 'success'; data: User } | { status: 'error'; error: string } No more "loading && data && !error" checks. TypeScript narrows the type automatically. 4. Branded types for IDs type UserId = string & { __brand: 'UserId' } type PostId = string & { __brand: 'PostId' } Prevents accidentally passing a PostId where UserId is expected. Catches bugs at compile time. 5. Const assertions for constants const ROLES = ['admin', 'user', 'guest'] as const; type Role = typeof ROLES[number]; Type is 'admin' | 'user' | 'guest', not string. No magic strings. These patterns add maybe 5 minutes of setup. They've saved me hours of debugging. #TypeScript #DeveloperTools #Frontend
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