Day 13: Promise APIs in JavaScript (Promise.all, race, allSettled, any) If you really want to master async JavaScript, you must understand the Promise APIs 💡 JavaScript gives us powerful methods to handle multiple promises. 🔹 1️⃣ Promise.all() 👉 Waits for all promises to succeed 👉 Fails immediately if any one fails Promise.all([api1(), api2(), api3()]) .then(results => console.log(results)) .catch(error => console.log(error)); ✅ Best when all results are required ❌ One failure = everything fails 🔹 2️⃣ Promise.race() 👉 Returns the first promise that settles (resolve or reject) Promise.race([api1(), api2(), api3()]) .then(result => console.log(result)) .catch(error => console.log(error)); ✅ Useful for timeout logic 🔹 3️⃣ Promise.allSettled() 👉 Waits for all promises 👉 Returns status of each (fulfilled/rejected) Promise.allSettled([api1(), api2()]) .then(results => console.log(results)); ✅ Useful when you want all results, even if some fail 🔹 4️⃣ Promise.any() 👉 Returns the first fulfilled promise 👉 Ignores rejected ones Promise.any([api1(), api2()]) .then(result => console.log(result)) .catch(error => console.log(error)); ✅ Best when you only need one successful response 🔥 Quick Summary • Promise.all → All must succeed • Promise.race → First settled wins • Promise.allSettled → Get all results • Promise.any → First success wins 🧠 Why Important? ✔️ Used in real-world APIs ✔️ Common frontend interview question ✔️ Helps optimize async performance #JavaScript #Promises #AsyncJavaScript #webdevelopment #LearnInPublic
Mastering JavaScript Promises: Promise.all, race, allSettled, any
More Relevant Posts
-
Most Front-End Developers Use JavaScript Async Code Every Day… But 90% Don’t Actually Understand the Event Loop. Here’s a simple question that often surprises developers: What will this code print? console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Most people answer: Start Timeout Promise End But the correct output is: Start End Promise Timeout Why? Because of something many developers overlook: Microtasks vs Macrotasks. JavaScript execution follows this order: 1️⃣ Call Stack 2️⃣ Microtask Queue (Promises, MutationObserver) 3️⃣ Macrotask Queue (setTimeout, setInterval, DOM events) Even if "setTimeout" is set to 0ms, it still goes into the Macrotask Queue, which runs after all microtasks are completed. So the order becomes: Start → End → Promise → Timeout Understanding this isn't just theory. It affects: • React rendering behavior • Async state updates • Performance optimization • Debugging weird async bugs The difference between a beginner and an advanced JavaScript developer is not knowing async/await… It’s understanding what happens under the hood when async code runs. If you're a Front-End developer, mastering the Event Loop is one of the highest leverage skills you can learn.
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗡𝗮𝘁𝘂𝗿𝗲 𝗼𝗳 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 When you start writing JavaScript, it seems simple. Code runs from top to bottom, line by line. But then you learn about timers like setTimeout and setInterval. Things get weird. You find out JavaScript is single-threaded. It can only do one thing at a time. Think of a fast-food restaurant with one cashier. This cashier is like the Call Stack. It does things in the order they were received. If a function takes too long, it won't freeze your app. But how does it work? There are key players: Web APIs, the Callback Queue, and the Event Loop. JavaScript doesn't have built-in tools for long tasks like network calls. The environment, like a browser or Node.js, handles these tasks. Web APIs handle tasks in the background. When done, they add the result to the Callback Queue. The Event Loop checks the Call Stack. If it's empty, it moves the first task from the Queue to the Call Stack. There are two types of Callback Queues: Macro Task Queue for timers and Micro Task Queue for promises. Over time, async code in JavaScript evolved. We used callback functions, then promises, and now async/await. Async/await makes async code look sync. You declare a function with async and use await to pause it. This lets other code run, making it non-blocking. JavaScript is single-threaded, but the Event Loop and environment give it async superpowers. Source: https://lnkd.in/gERccB3C
To view or add a comment, sign in
-
What is non-blocking operation in JavaScript? Non-blocking in JavaScript means your code can start a slow task (like a timer, API call, or file read) and keep executing other code instead of waiting and freezing the main thread. Brief explanation JavaScript runs on a single thread with an event loop. When it hits an async operation (setTimeout, fetch, I/O), that work is offloaded to Web APIs / the system. When the async work finishes, its callback is queued and later pushed back to the call stack by the event loop, so the main thread never blocks while waiting. Simple example for your post js console.log("Start"); setTimeout(() => { console.log("Inside setTimeout (runs later)"); }, 2000); // 2 seconds console.log("End"); Output: Start End Inside setTimeout (runs later) Even though the timer is 2 seconds, "End" prints immediately. The setTimeout callback is handled in the background and executed later via the event loop, so the main thread is not blocked. Ready-to-post LinkedIn text JavaScript is single-threaded, but it still feels “non-blocking” thanks to the event loop.🧵 When we use functions like setTimeout, fetch, or other async APIs, JavaScript does not wait for them to finish. Instead, the heavy work is offloaded to the browser/Web APIs or Node’s libuv layer. Once the operation completes, its callback is pushed to a queue, and the event loop runs it when the call stack is free. Example: js console.log("Start"); setTimeout(() => { console.log("Inside setTimeout (runs later)"); }, 2000); console.log("End"); Output order: Start → End → Inside setTimeout (runs later) This is a simple demo of non-blocking behavior: while the timer is counting in the background, the main thread continues executing the rest of the code, keeping the UI responsive and allowing servers to handle many requests concurrently #javascript #frontendDevelopment #react #reactjs
To view or add a comment, sign in
-
Understanding JavaScript's Asynchronous Magic ✨ Ever wondered how JavaScript, a single-threaded language, handles complex tasks without freezing your application? It's all thanks to its clever asynchronous nature! JavaScript executes code synchronously using a call stack. If a long-running task runs here, it blocks everything. Imagine your entire web page freezing while waiting for a single operation – not ideal for user experience! To avoid this, JavaScript delegates asynchronous tasks (like timers, network requests, or database calls) to the browser's Web APIs. These APIs work in the background, freeing up the main JavaScript thread to continue executing other code. Once an asynchronous task is complete, its associated callback function isn't immediately thrown back into the call stack. Instead, it's placed into a queue: Microtask Queue: For promises and queueMicrotask. Callback Queue (or Macrotask Queue): For timers (setTimeout, setInterval), I/O, and UI rendering. This is where the Event Loop comes in! 🔄 The Event Loop constantly monitors the call stack. When the call stack is empty (meaning all synchronous code has finished executing), the Event Loop steps in. It first checks the Microtask Queue and pushes any pending callbacks onto the call stack for execution. Once the Microtask Queue is empty, it then moves on to the Callback Queue, taking the oldest callback and pushing it onto the call stack. This continuous dance between the call stack, Web APIs, queues, and the Event Loop is how JavaScript achieves its non-blocking asynchronous behavior, giving users a smooth and responsive experience – all without ever becoming truly multi-threaded! Pretty neat, right? This fundamental concept is crucial for building performant and scalable web applications. #JavaScript #WebDevelopment #Frontend #Programming #AsynchronousJS #EventLoop
To view or add a comment, sign in
-
-
How JavaScript Actually Works Behind the Scenes ? When I first started writing JavaScript, it felt simple. Write a line of code. Run it. See the result. But recently, I started asking a deeper question: What’s actually happening behind the scenes? ⚙️ JavaScript doesn’t run alone It runs inside an engine (like V8 in Chrome). That engine reads the code, compiles it, and executes it. But here’s where it gets interesting! 📦 The Call Stack JavaScript uses something called a call stack to manage execution. Functions are pushed onto the stack when called. Once they finish, they’re popped off. This is why JavaScript is single-threaded — it executes one thing at a time, in order. ⏳ But what about async tasks? Things like: • setTimeout • API calls • Event listeners They don’t block the main thread. Instead, they go to the browser’s Web APIs, and once ready, they move to something called the Callback Queue. Then the Event Loop checks if the call stack is empty — and if it is, it pushes the callback into the stack. That’s how JavaScript handles asynchronous behavior without freezing the page 🚀 💡 The biggest realization for me? JavaScript isn’t “magic.” It’s a system working step by step — stack, queue, event loop. Understanding this changed how I debug and write async code. Now concepts like promises and async/await make much more sense. The more I learn, the more I realize — knowing what happens behind the scenes makes you a stronger developer.
To view or add a comment, sign in
-
-
JavaScript is easy to start with - but surprisingly hard to truly understand. Many developers can write JavaScript. Far fewer understand what actually happens under the hood. And that difference is often what separates someone who just writes code from someone who can truly reason about it. Here are a few core JavaScript internals every developer should understand: 🔹 Execution Context & Call Stack JavaScript code runs inside execution contexts. Each function call creates a new execution context that gets pushed onto the call stack. Understanding this explains recursion behavior, stack overflows, and how scope is resolved during execution. 🔹 Event Loop JavaScript itself runs on a single thread, but asynchronous behavior is enabled by the runtime (e.g., the browser or Node.js). The event loop coordinates the call stack, task queue (macrotasks), and microtask queue (Promises, queueMicrotask, etc.) to decide when callbacks are executed. 🔹 Closures A closure occurs when a function retains access to variables from its lexical scope, even after the outer function has finished executing. Closures are widely used for encapsulation, stateful functions, and many library/framework patterns. 🔹 Prototypes & Inheritance JavaScript uses prototype-based inheritance. Objects can inherit properties and methods through the prototype chain. Even modern "class" syntax is syntactic sugar on top of this mechanism. 🔹 Hoisting During the creation phase of an execution context, declarations are processed before code execution. Function declarations are fully hoisted, while "var" is hoisted but initialized with "undefined". "let" and "const" are hoisted but remain in the Temporal Dead Zone until initialization. 🔹 The "this" keyword "this" is determined by how a function is called, not where it is defined. Its value depends on the call-site (method call, constructor call, explicit binding with "call/apply/bind", or arrow functions which capture "this" lexically). Once you understand these mechanics, JavaScript stops feeling "magical" - and becomes far more predictable. What JavaScript concept took you the longest to fully understand? #javascript #webdevelopment #softwareengineering #frontend
To view or add a comment, sign in
-
-
Is Vanilla HTML, CSS, and JavaScript Dead? Absolutely not. But the habit of critical thinking before picking a tech stack seems to be on life support. Too many developers blindly jump onto heavy frameworks like React simply because it's the current industry default. They skip the vital factor checks, defaulting to massive JavaScript bundles to build what are essentially static 5-page brochures. It’s the equivalent of using a sledgehammer to crack a walnut it gets the job done, but it creates an unnecessary mess. Why must you evaluate before picking a stack? Because the stack dictates the product's entire lifecycle. Unnecessary frameworks introduce bloated bundle sizes, slower load times, fragile dependencies, and expensive technical debt that the client eventually has to pay for. The Power of the Basics Sometimes, going back to pure HTML, CSS, and vanilla JS is the ultimate professional move. It offers unmatched speed, simplicity, and longevity for content-heavy or static projects. I recently helped a technical team audit the architecture for a client's portfolio site. The initial proposal was a complex, overkill React application. I advised pivoting back to raw HTML, CSS, and JavaScript. The result? Blazing-fast load times, flawless SEO out of the box, and a client who won't have to pay a developer just to update NPM packages next year. Don't let framework hype dictate your builds. Let the project's actual needs make the call. #webdev #webdevelopers #frontenddev #frontendEnngineer
To view or add a comment, sign in
-
Is Vanilla HTML, CSS, and JavaScript Dead? Absolutely not. But the habit of critical thinking before picking a tech stack seems to be on life support. Too many developers blindly jump onto heavy frameworks like React simply because it's the current industry default. They skip the vital factor checks, defaulting to massive JavaScript bundles to build what are essentially static 5-page brochures. It’s the equivalent of using a sledgehammer to crack a walnut it gets the job done, but it creates an unnecessary mess. Why must you evaluate before picking a stack? Because the stack dictates the product's entire lifecycle. Unnecessary frameworks introduce bloated bundle sizes, slower load times, fragile dependencies, and expensive technical debt that the client eventually has to pay for. The Power of the Basics Sometimes, going back to pure HTML, CSS, and vanilla JS is the ultimate professional move. It offers unmatched speed, simplicity, and longevity for content-heavy or static projects. I recently helped a technical team audit the architecture for a client's portfolio site. The initial proposal was a complex, overkill React application. I advised pivoting back to raw HTML, CSS, and JavaScript. The result? Blazing-fast load times, flawless SEO out of the box, and a client who won't have to pay a developer just to update NPM packages next year. Don't let framework hype dictate your builds. Let the project's actual needs make the call. hashtag #webdev #webdevelopers #frontenddev #frontendEngineer
To view or add a comment, sign in
-
🚀 20 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 𝗧𝗵𝗮𝘁 𝗖𝗮𝗻 𝗛𝗲𝗹𝗽 𝗬𝗼𝘂 𝗖𝗿𝗮𝗰𝗸 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄𝘀 If you’re preparing for frontend roles, make sure you’re confident with these core JavaScript concepts: 1. What are higher-order functions in JavaScript, and can you give an example? 2. What is destructuring in JavaScript, and why is it useful? 3. What are template literals, and how do they improve string handling? 4. How does the spread operator (…) work? 5. What is the rest parameter, and how is it different from the arguments object? 6. What is the difference between an object and an array? 7. How do you properly clone an object or an array? 8. What do Object.keys(), Object.values(), and Object.entries() do? 9. How does the map() method work, and when should you use it? 10. What is the difference between map() and forEach()? 11. What is event delegation, and why is it powerful? 12. What are JavaScript modules, and how do import/export work? 13. What is the prototype chain, and how does inheritance happen in JavaScript? 14. What is the difference between bind(), call(), and apply()? 15. How does JavaScript handle equality comparisons (== vs ===)? 16. What is the DOM, and how does JavaScript interact with it? 17. How do you prevent default behavior and stop event propagation? 18. What is the difference between synchronous and asynchronous code? 19. What is the difference between a native event object and a custom event? 20. How do you optimize performance in JavaScript applications? If you can clearly explain these concepts with examples, you’re in a strong position for most frontend interviews. #JavaScript #FrontendDevelopment #WebDevelopment #InterviewPreparation #ReactJS #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Understanding Global Execution Context in JavaScript Have you ever wondered what happens behind the scenes when a JavaScript program starts running? Behind the scenes, JavaScript doesn’t just run your code directly… it first creates a special environment responsible for managing memory and executing code. That is called Execution context. There are 3 types of Execution Contexts: 1) Global Execution Context: 2) Function Execution Context: 👉 Created every time a function is called. Each function gets its own separate execution context It contains: >> Local variables >>Function arguments >>Scope information 👉 Important: If you call a function 5 times → ✔️ 5 different execution contexts are created. 3) Eval Execution Context (Rare ⚠️) 👉 Created when using eval() eval("console.log('Hello')"); >> Rarely used in real projects >> Not recommended (security + performance issues. What is the Global Execution Context? The Global Execution Context is the default environment where JavaScript code begins execution. Whenever a JavaScript program runs, the engine first creates the Global Execution Context. What does the Global Execution Context contain? 1️⃣ Global Object: ->In browsers, the global object is window. 2️⃣ this keyword: ->At the global level, this refers to the global object. 3️⃣ Memory for variables and functions: ->JavaScript allocates memory for variables and functions before executing the code. JavaScript runs code in two phases 1️⃣ Memory Creation Phase: ->Variables are stored with the value undefined ->Functions are stored entirely in memory 2️⃣ Code Execution Phase: ->JavaScript executes the code line by line ->Variables receive their actual values Example: var name = "JavaScript"; function greet() { console.log("Hello")} greet(); Before execution, JavaScript stores: name → undefined greet → function Then the code runs line by line. 💬 Question: How many Execution Contexts can exist at the same time in JavaScript? #JavaScript #WebDevelopment #Programming #FrontendDevelopment
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