Mastering JavaScript Promises for Cleaner Async Code

Understanding Promises in JavaScript (Made Simple) If you’ve ever struggled with messy callbacks, this is for you - The Problem: Handling asynchronous operations (API calls, timers, etc.) using callbacks often leads to: • Callback hell • Hard-to-read code • Difficult error handling The Solution: Promises A Promise represents the future result of an async operation. It has 3 states: • Pending • Fulfilled • Rejected  Basic Example: const fetchData = new Promise((resolve, reject) => {   let success = true;   if (success) {     resolve("Data fetched");   } else {     reject("Error fetching data");   } }); fetchData   .then(res => console.log(res))   .catch(err => console.log(err)); Why Promises Matter: • Cleaner than callbacks • Better error handling • Easy chaining • Foundation for async/await Pro Tip: If you’re using async/await, you’re already using Promises under the hood! async function getData() {   try {     const res = await fetchData;     console.log(res);   } catch (err) {     console.log(err);   } } Bonus 1: Promise.all() (Must Know) Promise.all([p1, p2, p3])   .then(results => console.log(results))   .catch(err => console.log(err)); Runs all in parallel, fails fast if any fails. Bonus 2: Promise.allSettled() (Underrated) Promise.allSettled([p1, p2, p3])   .then(results => console.log(results)); Returns all results (success + failure) Bonus 3: Promise.race() (Speed Matters) Returns the first settled promise (either success OR failure). const p1 = new Promise(res => setTimeout(() => res("API 1"), 2000)); const p2 = new Promise((_, rej) => setTimeout(() => rej("API 2 failed"), 1000)); Promise.race([p1, p2])   .then(res => console.log(res))   .catch(err => console.log(err)); // "API 2 failed" Key Point: • Fastest result wins • Can return success OR failure • Useful for timeouts Bonus 4: Promise.any() (First Success Wins) Returns the first fulfilled promise and ignores failures. const p1 = Promise.reject("API 1 failed"); const p2 = new Promise(res => setTimeout(() => res("API 2 success"), 1500)); const p3 = new Promise(res => setTimeout(() => res("API 3 success"), 2000)); Promise.any([p1, p2, p3])   .then(res => console.log(res)) // "API 2 success"   .catch(err => console.log(err)); Key Point: • Ignores rejected promises • Fails only if ALL promises fail • Best for fallback APIs Real-world usage: • Race → API timeout handling • Any → fallback API strategy • All → parallel API calls • AllSettled → partial results handling Which Promise method do you use the most in real projects? #JavaScript #WebDevelopment #FrontendDeveloper #AsyncProgramming #CodingTips #ReactJS #Angular #SoftwareDevelopment

Actively looking for Frontend / React Native Developer roles. Open to opportunities in Kolkata or Remote. Happy to connect with recruiters and hiring managers.

Like
Reply

To view or add a comment, sign in

Explore content categories