Promises help us handle async tasks like fetching data without blocking code execution. Here are 4 common Promise methods with simple examples 👇 --- 💡 1️⃣ Promise.all() Waits for all promises to finish — fails if any one fails. Promise.all([ Promise.resolve("A"), Promise.resolve("B") ]).then(result => console.log(result)); ✅ Output: ["A", "B"] --- 💡 2️⃣ Promise.any() Returns the first successful promise. Promise.any([ Promise.reject("Error"), Promise.resolve("Success") ]).then(result => console.log(result)); ✅ Output: "Success" --- 💡 3️⃣ Promise.race() Returns the first promise that finishes (success or fail). Promise.race([ Promise.resolve("Fast"), Promise.reject("Error") ]).then(result => console.log(result)); ✅ Output: "Fast" --- 💡 4️⃣ Promise.allSettled() Waits for all promises — returns both success and failure results. Promise.allSettled([ Promise.resolve("Done"), Promise.reject("Failed") ]).then(result => console.log(result)); ✅ Output: [ { status: "fulfilled", value: "Done" }, { status: "rejected", reason: "Failed" } ] --- ✨ Summary: 🟢 all() → Waits for all success 🟢 any() → First success 🟢 race() → First finished 🟢 allSettled() → Get all results #JavaScript #Promises #WebDevelopment #Async #Coding
"Understanding Promise Methods in JavaScript"
More Relevant Posts
-
🚀 Understanding Iterators and Generators in JavaScript If you've ever worked with data streams, APIs, or pagination, you’ve already touched concepts related to Iterators and Generators — even if you didn’t realize it. Here’s how I understand them 👇 🔹 Iterator An iterator is an object that lets you access data one piece at a time. You keep calling .next() until all values are done. It’s like flipping through pages in a book — one by one. const arr = [1, 2, 3]; const it = arr[Symbol.iterator](); console.log(it.next()); // { value: 1, done: false } console.log(it.next()); // { value: 2, done: false } console.log(it.next()); // { value: 3, done: false } 🔹 Generator A generator (function*) automatically creates an iterator for you. It can pause and resume execution using the yield keyword. Think of it as a movie you can pause and continue from the same point. function* numbers() { yield 1; yield 2; yield 3; } const gen = numbers(); console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false } 💡 When to use When you want to handle large data step-by-step When you need lazy loading or pagination When working with async data streams 🧠 In short: > Iterator gives you control over data flow. Generator makes that control easy and more powerful. --- #JavaScript #WebDevelopment #Coding #Generators #Iterators #Frontend #Learning #AsyncJS #Developers #TechTips ---
To view or add a comment, sign in
-
-
Async / Await: async / await lets you write asynchronous code that looks synchronous. async function fetchUsers() { try { const res = await fetch("https://lnkd.in/gq8n7UnX"); const users = await res.json(); console.log("Users fetched:", users); users.forEach(user => console.log(user.name, "-", user.email)); } catch (err) { console.error("Error fetching users:", err); } } fetchUsers(); console.log("This runs while fetchUsers waits for API"); Benefits: Cleaner, readable syntax Easier error handling Sequential logic without nested callbacks Using async JavaScript effectively helps create smoother, more responsive applications.
To view or add a comment, sign in
-
𝐓𝐚𝐦𝐢𝐧𝐠 𝐀𝐬𝐲𝐧𝐜 𝐓𝐚𝐬𝐤𝐬: 𝐏𝐫𝐨𝐦𝐢𝐬𝐞𝐬 𝐚𝐧𝐝 𝐭𝐡𝐞 𝐃𝐫𝐞𝐚𝐦 𝐓𝐞𝐚𝐦 𝐂𝐨𝐦𝐛𝐢𝐧𝐚𝐭𝐨𝐫𝐬 Ever felt like you're 𝐰𝐫𝐞𝐬𝐭𝐥𝐢𝐧𝐠 with 𝐚𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐜𝐨𝐝𝐞? You know, when you need to 𝐟𝐞𝐭𝐜𝐡 𝐝𝐚𝐭𝐚 from 𝐭𝐡𝐫𝐞𝐞 𝐝𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐭 𝐀𝐏𝐈𝐬, but they all need to finish 𝐛𝐞𝐟𝐨𝐫𝐞 you can 𝐫𝐞𝐧𝐝𝐞𝐫 the 𝐩𝐚𝐠𝐞? Enter 𝐏𝐫𝐨𝐦𝐢𝐬𝐞𝐬 and their incredible 𝐜𝐨𝐦𝐛𝐢𝐧𝐚𝐭𝐨𝐫 𝐦𝐞𝐭𝐡𝐨𝐝𝐬—the superheroes of modern JavaScript! 𝐏𝐫𝐨𝐦𝐢𝐬𝐞𝐬 handle the "𝐰𝐡𝐞𝐧 𝐭𝐡𝐢𝐬 𝐞𝐯𝐞𝐧𝐭𝐮𝐚𝐥𝐥𝐲 𝐡𝐚𝐩𝐩𝐞𝐧𝐬, 𝐝𝐨 𝐭𝐡𝐚𝐭" logic, keeping your code clean. But the real magic lies in their combinators, which let you orchestrate multiple async operations like a pro conductor: 𝐏𝐫𝐨𝐦𝐢𝐬𝐞.𝐚𝐥𝐥(): This is your "𝐀𝐥𝐥 𝐨𝐫 𝐍𝐨𝐭𝐡𝐢𝐧𝐠" strategy. Perfect for fetching data that must all succeed (e.g., getting a user's profile, settings, and friend list simultaneously). If one fails, they all fail fast. 𝐏𝐫𝐨𝐦𝐢𝐬𝐞.𝐫𝐚𝐜𝐞(): Need the 𝐟𝐚𝐬𝐭𝐞𝐬𝐭 𝐫𝐞𝐬𝐩𝐨𝐧𝐬𝐞? This method "races" multiple promises and returns the result of the first one to resolve or reject. Great for redundant server calls or a timeout mechanism. 𝐏𝐫𝐨𝐦𝐢𝐬𝐞.𝐚𝐥𝐥𝐒𝐞𝐭𝐭𝐥𝐞𝐝(): Want to 𝐤𝐧𝐨𝐰 𝐭𝐡𝐞 𝐨𝐮𝐭𝐜𝐨𝐦𝐞 𝐨𝐟 𝐞𝐯𝐞𝐫𝐲 𝐩𝐫𝐨𝐦𝐢𝐬𝐞, regardless of success or failure? Use this! Ideal for non-critical background tasks like logging or status updates where you need a full report. These methods literally turn callback code into elegant, readable async flows. They've saved me countless hours of debugging! 𝐔𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 when to use 𝐚𝐥𝐥(), 𝐫𝐚𝐜𝐞(), 𝐨𝐫 𝐚𝐥𝐥𝐒𝐞𝐭𝐭𝐥𝐞𝐝() is a true mark of an experienced developer. ➡️ 𝐅𝐨𝐥𝐥𝐨𝐰 𝐦𝐞 for more content on clean code, JavaScript, and developer insights! 👍 𝐒𝐡𝐚𝐫𝐞 this post if you found this breakdown helpful! 🔄 𝐑𝐞𝐩𝐨𝐬𝐭 to help a fellow developer tame their async tasks! #JavaScript #Promises #AsyncAwait #WebDevelopment #ProgrammingTips #CleanCode #TechSkills
To view or add a comment, sign in
-
Higher-Order Functions — The Hidden Power Behind Async JavaScript When I started working with APIs and async operations, my code quickly turned messy — retries, error handling, logging… all over the place. Then I discovered Higher-Order Functions (HOFs) — functions that can take or return other functions. This simple concept completely changed how I structure async workflows. Instead of repeating logic, I now wrap my functions with extra behavior like retry mechanisms, logging, and response tracking — all cleanly separated. It’s the same principle behind: - setTimeout() and callbacks - Array.map() / filter() - Express middleware Once you start using HOFs, you realize — modern JavaScript magic runs on this idea. ✨ 🔗 Read the full blog post here: 📝 Notion: https://lnkd.in/djZdNkkh 📝 Dev.to: https://lnkd.in/drM7kBE8 📝 Hashnode: https://lnkd.in/dMxfBYMh 📝 Medium: https://lnkd.in/d_z_B8Ei #JavaScript #WebDevelopment #AsyncProgramming #HigherOrderFunctions #CodingTips #Developers
To view or add a comment, sign in
-
-
There was a time when I was that developer who'd rather write tests than add types. "JavaScript is fine," I'd say. "Types just slow you down." Then came the incident. A simple prop rename. I updated it in one component, missed it in three others. The app compiled fine. Tests passed. Everything looked good. Until real users started hitting null reference errors everywhere. Spent half the night rolling back and patching. Could've been avoided if the compiler had just told me "hey, these three files are still expecting the old prop name." That's when it clicked. Here's what I wish I'd understood earlier: IntelliSense becomes actually useful. Before, autocomplete was just guessing. Now when I'm working with complex objects, my editor knows exactly what properties exist. No more jumping between files to check structure. Breaking changes become visible instantly. When someone on the team modifies a shared data model, I don't find out during code review or worse, in staging. My IDE lights up the moment I pull their changes. Refactoring stops feeling dangerous. Renaming properties, restructuring interfaces, moving things around used to be a game of "did I catch every reference?" Now the type checker does that work for me. Documentation that actually stays current. Comments lie. Types don't. New team members can look at a function signature and immediately know what it expects and returns. The biggest surprise? I write code faster now, not slower. Yeah, there's an upfront cost defining types. But I'm not spending 20 minutes debugging why user.name is undefined anymore. I'm not asking in Slack "what shape does this API return again?" I'm not afraid to touch old code. TypeScript didn't make me a more careful developer. It made me a more confident one. If you've been putting it off because it seems like extra friction, I get it. I was there. But that friction you're avoiding? You're already paying for it in debugging time and production fires.
To view or add a comment, sign in
-
-
💡 ECMAScript 2025 is shaping up to be a game-changer for JavaScript developers. Iterators now support .map(), .filter(), .take(), and .drop() no more array conversions, just clean, lazy, and chainable data handling. Sets are also getting long-awaited upgrades like union, intersection, difference, and checks for subset/superset relationships. Other highlights include: RegExp.escape() for safer pattern handling JSON imports with { type: "json" } Promise.try() for smoother sync/async logic These additions may seem small, but together they make JavaScript feel more modern, expressive, and efficient.
To view or add a comment, sign in
-
-
Chaining Promises in JavaScript ✨ When working with asynchronous code, chaining Promises helps us execute multiple operations step by step — keeping our code clean, readable, and manageable.Instead of creating a callback hell, we can chain .then() methods to handle results sequentially. Here’s an example: function getData() { return new Promise((resolve) => { setTimeout(() => resolve("Step 1: Data fetched ✅"), 1000); }); } function processData() { return new Promise((resolve) => { setTimeout(() => resolve("Step 2: Data processed ⚙️"), 1000); }); } function showResult() { return new Promise((resolve) => { setTimeout(() => resolve("Step 3: Result displayed 🎯"), 1000); }); } getData() .then(response => { console.log(response); return processData(); }) .then(response => { console.log(response); return showResult(); }) .then(response => { console.log(response); }) .catch(error => { console.error("Error:", error); }); Each .then() waits for the previous Promise to complete before executing the next one — ensuring smooth and predictable flow. #JavaScript #Promises #AsyncProgramming #WebDevelopment #CodeNewbie #MERNStack #JSDeveloper #CodingJourney #LearnInPublic #WebDevelopers #FrontendDevelopment #100DaysOfCode #JavaScriptTips
To view or add a comment, sign in
-
𝐓𝐲𝐩𝐞𝐒𝐜𝐫𝐢𝐩𝐭 𝐠𝐢𝐯𝐞𝐬 𝐲𝐨𝐮 𝐭𝐲𝐩𝐞 𝐬𝐚𝐟𝐞𝐭𝐲... 𝐮𝐧𝐭𝐢𝐥 𝐫𝐮𝐧𝐭𝐢𝐦𝐞. You define perfect TypeScript interfaces for your API responses. Your IDE shows no errors. Your build passes. Everything looks perfect. Then production happens: the API returns null instead of an object. A number comes back as a string. An optional field is suddenly required. Your app crashes. TypeScript only checks types at compile time. It can't protect you from external data. 𝐓𝐡𝐚𝐭'𝐬 𝐰𝐡𝐞𝐫𝐞 𝐙𝐨𝐝 𝐜𝐨𝐦𝐞𝐬 𝐢𝐧. Zod lets you define schemas that validate data at runtime: → API responses actually match your types → Form inputs are validated before processing → Environment variables are checked on startup → Database queries return expected shapes You write one schema, and Zod automatically: ✓ Validates the data structure ✓ Infers TypeScript types ✓ Generates helpful error messages ✓ Transforms data if needed No more runtime surprises. No more try-catch blocks everywhere. No more "undefined is not an object" errors in production. Your TypeScript types finally work with real-world data, not just in your IDE. 𝐁𝐮𝐢𝐥𝐝𝐢𝐧𝐠 𝐓𝐲𝐩𝐞𝐒𝐜𝐫𝐢𝐩𝐭 𝐚𝐩𝐩𝐬 𝐭𝐡𝐚𝐭 𝐭𝐚𝐥𝐤 𝐭𝐨 𝐀𝐏𝐈𝐬? Zod ensures your runtime data actually matches your types. 💬 How do you handle API validation? Share your approach! #TypeScript #Zod #JavaScript #WebDevelopment #APIDevelopment #Frontend #Backend #Programming #DataValidation #DeveloperTools #NexalabsAgency
To view or add a comment, sign in
-
-
💛 𝗗𝗮𝘆 𝟰 — 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸𝘀, 𝗣𝗿𝗼𝗺𝗶𝘀𝗲𝘀 & 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁 Today I explored one of JavaScript’s most important topics — asynchronous programming. From callbacks ➝ promises ➝ async/await, each layer makes async code cleaner and more readable. 💡 𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸𝘀 function fetchData(callback) { setTimeout(() => callback("Data received ✔️"), 1000); } fetchData((msg) => console.log(msg)); ❗ Callback hell appears when callbacks get nested… 💡 𝗣𝗿𝗼𝗺𝗶𝘀𝗲𝘀 function fetchData() { return new Promise((resolve) => { setTimeout(() => resolve("Promise resolved ✔️"), 1000); }); } fetchData().then(console.log); 💡 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁 async function getData() { const data = await fetchData(); console.log(data); } getData(); 🧠 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴𝘀 ✅ Callbacks → basic async ✅ Promises → structured async ✅ Async/await → synchronous-style async #JavaScript #Async #Promises #Callbacks #100DaysOfCode #LearningEveryday
To view or add a comment, sign in
-
🚀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗗𝗲𝗲𝗽 𝗗𝗶𝘃𝗲: 𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝘁𝗵𝗲 𝗙𝗲𝘁𝗰𝗵 𝗔𝗣𝗜 💡 Say goodbye to old-school XMLHttpRequest! The Fetch API is the modern, promise-based way to make HTTP requests in JavaScript — simple, powerful, and elegant. ⚡ 🔹 𝗕𝗮𝘀𝗶𝗰 𝗙𝗲𝘁𝗰𝗵 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: fetch('https://lnkd.in/gWKpgMrT') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ✅ fetch() returns a Promise ✅ response.json() converts response to JSON ✅ .catch() ensures error handling 🔹 𝗖𝗹𝗲𝗮𝗻𝗲𝗿 𝗦𝘆𝗻𝘁𝗮𝘅 𝘄𝗶𝘁𝗵 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁: async function getData() { try { const response = await fetch('https://lnkd.in/gWKpgMrT'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } getData(); ✨ No more nested .then() chains — just clean, readable async code! 💡 𝗣𝗿𝗼 𝗧𝗶𝗽𝘀: 🔸 Always handle network errors 🔸 Add headers for authentication & content-type 🔸 Supports GET, POST, PUT, DELETE and more Credit 💳 🫡 Sameer Basha Shaik 🚀 The Fetch API is a must-know tool for every frontend developer — perfect for fetching data, integrating APIs, and building modern web applications! 🌐 #JavaScript #FetchAPI #WebDevelopment #AsyncAwait #Frontend #CodingTips #CleanCode #DeveloperCommunity #Promises #LearnToCode #jsdeveloper
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