Are you able to answer these Promises scenarios ? Scenario 1: You trigger 5 parallel API calls using Promise.all. Two of them reject immediately. Three are still running. Question: Will the remaining 3 promises stop executing? Answer: No. Promise.all fails fast in terms of result, but it does NOT cancel the other promises. JavaScript has no built-in cancellation mechanism. The remaining promises continue running in the background. Interview follow-up: So how would you actually cancel them? Correct direction: AbortController (for fetch) or a custom cancellation pattern. Promise.all does not give you control over cancellation. Scenario 2: You use Promise.any with 4 APIs. All of them fail. Question: What does it throw? Answer: It throws an AggregateError, not a normal Error. And inside it, you get an errors array containing all rejection reasons. Many experienced developers miss this. Scenario 3: You use Promise.race for request timeout handling. Example logic: Race between API call and a timeout promise. Question: What happens if the API resolves after timeout already rejected? Answer: The API promise still resolves later. Race only determines which result you get first. It does not stop the slower promise. This creates hidden memory leaks if you don’t abort the request. Scenario 4: You want: Return first successful API. But if all fail, show a combined error report. Which method? Correct answer: Promise.any. But here’s the catch: If your environment doesn’t support it (older Node versions), you need a polyfill or custom implementation. Tip: Promise.all → Fail fast Promise.allSettled → Never fail Promise.race → First settled wins Promise.any → First success wins But none of them cancel anything. For more insightful content checkout below: 🟦 𝑳𝒊𝒏𝒌𝒆𝒅𝑰𝒏 - https://lnkd.in/dwi3tV83 ⬛ 𝑮𝒊𝒕𝑯𝒖𝒃 - https://lnkd.in/dkW958Tj 🟥 𝒀𝒐𝒖𝑻𝒖𝒃𝒆 - https://lnkd.in/dDig2j75 or Priya Frontend Vlogz 🔷 𝐓𝐰𝐢𝐭𝐭𝐞𝐫 - https://lnkd.in/dyfEuJNt #frontend #javascript #react #reactjs #html #css #typescript #es6 #interviewquestions #interview #interviewpreparation
JavaScript Promises: Canceling and Handling Failures
More Relevant Posts
-
🚀 𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐮𝐬𝐞𝐒𝐭𝐚𝐭𝐞 𝐢𝐧 𝐑𝐞𝐚𝐜𝐭: 𝐓𝐡𝐞 𝐅𝐨𝐮𝐧𝐝𝐚𝐭𝐢𝐨𝐧 𝐨𝐟 𝐃𝐲𝐧𝐚𝐦𝐢𝐜 𝐀𝐩𝐩𝐬 Ever wondered how a simple click can change a whole webpage? That’s the magic of State. In React, useState is the most fundamental Hook you’ll use to bring your interfaces to life. 🔹 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐮𝐬𝐞𝐒𝐭𝐚𝐭𝐞? It’s a Hook that allows you to add state to functional components. When the state changes, React automatically re-renders the component to reflect the new data. 🔹 𝐓𝐡𝐞 𝐒𝐲𝐧𝐭𝐚𝐱 const [state, setState] = useState(initialValue); -- state: The current value. -- setState: The function to update the value. -- initialValue: The starting point (number, string, etc.). 🔹 𝐒𝐢𝐦𝐩𝐥𝐞 𝐂𝐨𝐮𝐧𝐭𝐞𝐫 𝐄𝐱𝐚𝐦𝐩𝐥𝐞 import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <h1>𝐂𝐨𝐮𝐧𝐭: {count}</h1> <button onClick={() => setCount(count + 1)}>𝐈𝐧𝐜𝐫𝐞𝐦𝐞𝐧𝐭</button> </div> ); } 🔹 𝐏𝐫𝐨 𝐓𝐢𝐩𝐬 𝐟𝐨𝐫 𝐮𝐬𝐞𝐒𝐭𝐚𝐭𝐞 -- 𝐃𝐨𝐧'𝐭 𝐦𝐮𝐭𝐚𝐭𝐞 𝐬𝐭𝐚𝐭𝐞 𝐝𝐢𝐫𝐞𝐜𝐭𝐥𝐲: Never do count = count + 1. Always use the setter function (setCount). -- 𝐀𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐍𝐚𝐭𝐮𝐫𝐞: State updates aren't immediate. Use functional updates if you need the previous state: setCount(prev => prev + 1). -- 𝐈𝐧𝐢𝐭𝐢𝐚𝐥 𝐑𝐞𝐧𝐝𝐞𝐫: The initial value is only used during the first render. 𝐖𝐡𝐚𝐭’𝐬 𝐭𝐡𝐞 𝐦𝐨𝐬𝐭 𝐜𝐨𝐦𝐩𝐥𝐞𝐱 𝐬𝐭𝐚𝐭𝐞 𝐲𝐨𝐮’𝐯𝐞 𝐦𝐚𝐧𝐚𝐠𝐞𝐝 𝐢𝐧 𝐚 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭? Let’s discuss in the comments! 👇 Feel free to reach me out for any career mentoring Naveen .G.R|CareerByteCode #ReactJS #WebDevelopment #MERNStack #CodingTips #Javascript #Frontend
To view or add a comment, sign in
-
-
𝐀𝐫𝐞 𝐲𝐨𝐮 𝐛𝐚𝐭𝐭𝐥𝐢𝐧𝐠 𝐩𝐡𝐚𝐧𝐭𝐨𝐦 𝐛𝐮𝐠𝐬 𝐢𝐧 𝐲𝐨𝐮𝐫 𝐑𝐞𝐚𝐜𝐭 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭𝐬? 𝐘𝐨𝐮𝐫 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐦𝐢𝐠𝐡𝐭 𝐛𝐞 𝐬𝐢𝐥𝐞𝐧𝐭𝐥𝐲 𝐥𝐲𝐢𝐧𝐠 𝐭𝐨 𝐲𝐨𝐮. Often, we forget that `useEffect` captures variables from its surrounding scope. If those variables change but aren't in the dependency array, your effect might run with stale values from a previous render. This leads to subtle, hard-to-trace bugs where your logic seems correct but the data is wrong. Example: ```javascript function MyComponent({ userId }) { const [data, setData] = useState(null); // Problematic: Forgetting 'userId' in dependencies useEffect(() => { fetch(`/api/users/${userId}/data`).then(res => res.json()).then(setData); // userId is referenced, but not in dependency array }, []); // <-- STALE CLOSURE if userId changes! // Correct: userId is a dependency useEffect(() => { fetch(`/api/users/${userId}/data`).then(res => res.json()).then(setData); }, [userId]); // <-- Correctly re-runs when userId changes } ``` The linter usually warns you about this, but it's easy to dismiss or override. Understanding why it warns you about missing dependencies is crucial for stable and performant React applications. It’s not just about avoiding infinite loops; it's about guaranteeing your effects always operate with the latest state and props. What's your most common `useEffect` pitfall, or a bug that took you ages to trace back to a stale closure? #React #Frontend #TypeScript #JavaScript #WebDevelopment
To view or add a comment, sign in
-
Hare Krishna, #Javascript Developers🙇🏻 #React before 2019 was… complicated. 😵 If you wanted state or lifecycle methods, you had to use class components. More code ❗ More confusion❗ More `this` binding nightmares❗ Then in 2019, React introduced #Hooks in React 16.8 — and everything changed. 😄 Hooks allowed us to use state and lifecycle features inside functional components. 👉🏻No classes. 👉🏻No this. 👉🏻Cleaner logic. 🤔 What Was the Problem Before Hooks? Before hooks: 👉🏻Logic was duplicated across lifecycle methods 👉🏻Complex components became hard to maintain 👉🏻Sharing stateful logic required HOCs or Render Props (messy patterns) Hooks solved this by letting us reuse logic cleanly. 🧠 Simple Way to Remember Hooks' use cases: State? → useState Side effects? → useEffect DOM access? → useRef Performance optimization? → useMemo / useCallback Global shared data? → useContext 📿Chant Hare Krishna and Be Happy😊 #React #Frontend #JavaScript #WebDevelopment #Programming
To view or add a comment, sign in
-
-
⚠️ One tricky thing in React that confused me at first: useEffect dependencies At first, I thought useEffect just runs magically. But the truth is very simple 👇 🧠 Think of useEffect like this: “React, run this code after render, and re‑run it only when I tell you to.” That “telling” happens through the dependency array. ✅ Examples (super simple) useEffect(() => { console.log("Runs once"); }, []); ➡️ Runs only when component mounts but for the below case useEffect(() => { console.log("Runs when count changes"); }, [count]); ➡️ Runs every time count changes 🚨 The tricky part If you use a variable inside useEffect but forget to add it as a dependency, React will use an old value (stale data). 🧠 Rule to remember: If you use it inside useEffect, it should be in the dependency array. Once I understood this, useEffect stopped feeling scary 😊 Just logic + clarity. #React #JavaScript #Hooks #useEffect #Frontend #LearningInPublic
To view or add a comment, sign in
-
⚡ JavaScript Tip: Cleaner Promise Error Handling Developers often use this trick to catch sync errors in promise chains. ❌ Before Promise.resolve() .then(() => JSON.parse(data)) .then(result => console.log(result)) .catch(err => console.error(err)); ✅ Now with Promise.try() Promise.try(() => JSON.parse(data)) .then(result => console.log(result)) .catch(err => console.error(err)); ✔ Less boilerplate ✔ More readable async flows ✔ Cleaner error handling Sometimes the best language improvements are the smallest ones. Would you start using Promise.try() in your projects? #JavaScript #ESNext #NodeJS #WebDevelopment #CodingTips
To view or add a comment, sign in
-
-
𝐈𝐬 𝐲𝐨𝐮𝐫 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐫𝐮𝐧𝐧𝐢𝐧𝐠 𝐢𝐧𝐟𝐢𝐧𝐢𝐭𝐞𝐥𝐲 𝐨𝐫 𝐦𝐨𝐫𝐞 𝐭𝐡𝐚𝐧 𝐢𝐭 𝐬𝐡𝐨𝐮𝐥𝐝? 𝐓𝐡𝐞 𝐜𝐮𝐥𝐩𝐫𝐢𝐭 𝐢𝐬 𝐨𝐟𝐭𝐞𝐧 𝐬𝐢𝐦𝐩𝐥𝐞𝐫 𝐭𝐡𝐚𝐧 𝐲𝐨𝐮 𝐭𝐡𝐢𝐧𝐤. One of the most common pitfalls with `useEffect` in React is including non-primitive values (objects, arrays, functions) directly in its dependency array without proper handling. Every time your component re-renders, if you create a new object or array literal, or a new function instance, its reference changes. ```javascript useEffect(() => { /* fetch data using config */ }, [config]); ``` If `config` is an object created directly inside your component, even if its properties are identical, `useEffect` sees a new object reference on every render. This forces the effect to re-run, leading to unnecessary computation, API calls, or even infinite loops. **The Fix:** 1. **Destructure Primitives:** If you only need specific primitive properties from an object, destructure them out and add only those to the dependency array. ```javascript const { baseUrl, timeout } = apiConfig; ``` ```javascript useEffect(() => { // ... use baseUrl, timeout }, [baseUrl, timeout]); ``` 2. **Memoize Objects/Arrays:** If the entire object/array is a dependency and is derived from stable values, use `useMemo` to memoize its creation. This ensures its reference remains stable across renders unless its own dependencies change. ```javascript const stableConfig = useMemo(() => ({ baseUrl: '/api', timeout: 5000 }), []); ``` ```javascript useEffect(() => { // ... use stableConfig }, [stableConfig]); ``` 3. **Memoize Functions:** For functions, use `useCallback` to prevent new function instances on every render, ensuring a stable reference for your dependency array. Understanding how JavaScript handles reference equality is key to mastering `useEffect` and writing performant React applications. What's your go-to strategy for managing complex `useEffect` dependencies? #React #ReactJS #Frontend #JavaScript #WebDevelopment #Performance
To view or add a comment, sign in
-
You say you’re “comfortable with JavaScript”? Cool. Let’s test that. Answer these in the comments 👇 🧠 1. What will this output? Why? 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + []); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + {}); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨({} + []); Most developers get at least one wrong. ⚡ 2. Predict the output: 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘰𝘶𝘵𝘦𝘳() { 𝘭𝘦𝘵 𝘤𝘰𝘶𝘯𝘵 = 0; 𝘳𝘦𝘵𝘶𝘳𝘯 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘪𝘯𝘯𝘦𝘳() { 𝘤𝘰𝘶𝘯𝘵++; 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘤𝘰𝘶𝘯𝘵); }; } 𝘤𝘰𝘯𝘴𝘵 𝘧𝘯 = 𝘰𝘶𝘵𝘦𝘳(); 𝘧𝘯(); 𝘧𝘯(); 𝘧𝘯(); What concept is this testing? 🔥 3. What’s the difference between these two? 𝘖𝘣𝘫𝘦𝘤𝘵.𝘧𝘳𝘦𝘦𝘻𝘦(𝘰𝘣𝘫); 𝘖𝘣𝘫𝘦𝘤𝘵.𝘴𝘦𝘢𝘭(𝘰𝘣𝘫); When would you use one over the other in production? 🧩 4. True or False? 𝘵𝘺𝘱𝘦𝘰𝘧 𝘯𝘶𝘭𝘭 === "𝘰𝘣𝘫𝘦𝘤𝘵" 𝘐𝘧 𝘵𝘳𝘶𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 𝘐𝘧 𝘧𝘢𝘭𝘴𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 🚀 5. Async trap — what happens here? 𝘢𝘴𝘺𝘯𝘤 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘵𝘦𝘴𝘵() { 𝘳𝘦𝘵𝘶𝘳𝘯 42; } 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘵𝘦𝘴𝘵()); What exactly gets logged? If you can answer all 5 confidently, you’re not just “using” JavaScript. You understand it. Drop your answers below 👇 Let’s see who’s interview-ready. #javascript #frontenddeveloper #codinginterview #webdevelopment #softwareengineering #DAY73
To view or add a comment, sign in
-
setTimeout(fn, 0) runs immediately. Promise callbacks and setTimeout callbacks go in the same queue. The event loop is part of V8. ============================================= I believed all three. Every single one is wrong. I wrote about the mental model I had to completely unlearn — with interactive visualizations you can step through yourself. If you've ever had a spinner that never spins, an async forEach that silently fails, or a sequential await killing your performance without you noticing — this is the article I wish I'd read sooner. https://lnkd.in/gBTvuX2k #javascript #eventloop #webdev #frontend #v8 #async
To view or add a comment, sign in
-
7 Next.js mistakes I made so you don’t have to. 🔥 I spent 4 months debugging problems that shouldn’t have existed. Not because Next.js is hard. Because nobody told me I was doing it wrong. Here’s every mistake — and the fix — so you don’t waste the same time I did 👇 🔥 Mistake 1 — “use client” on everything I added it to every component “just to be safe.” It destroys your performance. Only leaf-level interactive components need it. Never layouts, never pages. 😫 Mistake 2 — Fetching data in useEffect I was writing useEffect(() => { fetch... }) in every page. Make your page async and fetch directly inside it. Data arrives with the HTML. Zero loading spinners. 🤔 Mistake 3 — Ignoring loading.tsx I spent hours building custom loading states. Then I discovered loading.tsx. Drop it next to any page and Next.js handles it automatically. I felt so stupid. 💥 Mistake 4 — Not using Suspense One slow database call was blocking my entire page. Wrap slow components in <Suspense> and stream everything else instantly while it loads. 🔐 Mistake 5 — Securing routes with useEffect I was doing useEffect(() => { if (!user) router.push('/login') }). The page flashes before the redirect. Use middleware.ts to block at the edge. No flash. No leak. I made all 5 of these in my first month. Most people never find out why their app feels slow or broken. Now you know. Which one were you making? Be honest — drop the number below 👇 Save this so you never make them again. 🔖 #NextJS #React #WebDevelopment #JavaScript #Frontend #Beginners #100DaysOfCode #NextJSTips #Programming #CleanCode #WebDev #CodingMistakes #LearnToCode
To view or add a comment, sign in
-
-
❓ Ever wondered why JavaScript sorts numbers “wrong”? Try this: [1, 10, 2].sort() Output: [1, 10, 2] Wait… why not [1, 2, 10]? 🤯 🧠 The reason: By default, JavaScript’s .sort() converts numbers into strings and sorts alphabetically. So it compares: "1", "10", "2" And "10" comes before "2". Sneaky default behavior 👀 ✅ The fix: arr.sort((a, b) => a - b) Now JS knows it’s numeric sorting. Tiny detail. Big difference. Sometimes bugs aren’t errors — they’re misunderstood defaults 😌 #JavaScript #WebDevelopment #CodingJourney #Frontend #Developers
To view or add a comment, sign in
More from this author
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
Good insight